How to use a variable in RegExp with a search method in Javascript?

I have a line:

var _codes = "1234,1414,5555,3333,2222,5566,4545";
var regex = new RegExp(/1234/i);
var _found = _codes.search(regex);

//this works sofar. 

nowi wants to do this with a variable:

like this:

var id = "1234";
regex = new RegExp("\\"+id+"\\/i");

but that will not work. any ideas?

Thank!

+3
source share
1 answer

When using the constructor, RegExpyou do not provide delimiters, and the flags go in the second argument.

var id = "1234";
regex = new RegExp(id, "i");

However, RegExp just for 1234s idoesn't really make sense. Use instead indexOf().

However, perhaps you really wanted to match the numbers surrounded \. In this case, leave them there.

+4
source

All Articles