How to put variable in regular expression match?

前端 未结 3 660
北海茫月
北海茫月 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:26

    You need to use the RegExp constructor instead of a regex literal.

    var string = 'asdgghjjkhkh';
    var string2 = 'a';
    var regex = new RegExp( string2, 'g' );
    string.match(regex);
    

    If you didn't need the global modifier, then you could just pass string2, and .match() will create the regex for you.

    string.match( string2 );
    

提交回复
热议问题