How to put variable in regular expression match?

前端 未结 3 651
北海茫月
北海茫月 2020-12-23 11:10

I have

var string1 = \'asdgghjajakhakhdsadsafdgawerwweadf\';
var string2 = \'a\';
string1.match(\"\\/\"+string2+\"\\/g\").length;

So with t

3条回答
  •  感情败类
    2020-12-23 11:38

    If you are merely looking to check whether a string contains another string, then your best bet is simply to use match() without a regex.

    You may object: But I need a regex to check for classes, like \s, to define complicated patterns, etc..

    In that case: You will need change the syntax even more, double-escaping your classes and dropping starting/ending / regex indicator symbols.

    Imagine this regex...

    someString.match(/\bcool|tubular\b);
    

    The exact equivalent of this, when using a new new RegExp(), is...

    someStringRegex = new RegExp('\\bcool|tubular\\b');
    

    Two things happened in this transition:

    • Drop the opening and closing / (otherwise, your regex will fail).
    • Double escape your character classes, like \b becomes \\b for word borders, and \w becomes \\w for whitespace, etc. (otherwise, your regex will fail).

提交回复
热议问题