Variable inside a javascript regular expression
javascript, regex
Solution
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
Problem
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