Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable inside a javascript regular expression

I've looked at a lot of similar questions about this kind of problem but they haven't solved my problem...

This is the string that I've to match: "|6[1]|" where the "6" is a variable that I've to put inside the regexp.

I've tried to create one (pid is the variable that contain the number):

var filter = new RegExp("/\|"+pid+"[\d*\]\|/");

It's look not working.. tryed with chrome console

enter image description here

like image 822
manuelprojects Avatar asked Nov 22 '25 18:11

manuelprojects


1 Answers

When you construct a regular expression from a string you do not need the / delimiters:

var filter = new RegExp("\|"+pid+"[\d*\]\|");

The / token is used to signify the start/end of a regular expression literal to the parser, much like the " and ' tokens signify the start/end of a string literal. In this case you're using a string literal so you don't need the regexp literal delimiters.

Your actual regex doesn't work because:

  • You've missed the escape character off the opening square bracket
  • You need to escape literal backslashes when building a regex from a string

So the working code should be:

var filter = new RegExp("\\|"+pid+"\\[\\d*\\]\\|");
//                       ^         ^^ ^   ^  ^ Add in these backslashes
like image 141
James Allardice Avatar answered Nov 24 '25 08:11

James Allardice



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!