How to remove a single class only in Javascript using Regex?

This question already has an answer here:

  • How do you use a variable in a regular expression? 16 answers

  • Use the RegExp constructor instead of a RegExp literal. The constructor takes a string as its first param, so you can build it any way you like.

    function remove_class(div, klass) {
        div.className = div.className.replace( new RegExp('(?:^|s)' + klass + '(?!S)'), '' );
    }
    

    Notice that no delimiters (the leading and trailing forward slashes) are needed when using the constructor.


    相反使用/ regexp /语法你可以使用RegExp:像这样:

    function remove_class(div, klass) {
        var regex = new RegExp('/(?:^|s)' + klass + '(?!S)/');
        div.className = div.className.replace( regex , '' );
    }
    

    You can create the regexp like so:

    var re = new RegExp("regex","g");
    

    Check out https://stackoverflow.com/a/494046/1778812

    链接地址: http://www.djcxy.com/p/76830.html

    上一篇: 如何动态创建正则表达式以在.match Javascript中使用?

    下一篇: 如何使用正则表达式在Javascript中删除单个类?