javascript tutorial - [Solved-5 Solutions] Variable in a regular expression - javascript - java script - javascript array
Problem:
How do you use a variable in a regular expression?
Solution 1:
Instead of using the /regex/g syntax, you can construct a new RegExp object:
Solution 2:
This yields "regex matching ." . However, it will fail if str1 is ".". we'd expect the result to be "pattern matching regex", replacing the period with "regex", but it'll turn
This is because, although "." is a String, in the RegExp constructor it's still interpreted as a regular expression, meaning any non-line-break character, meaning every character in the string. For this purpose, the following function may be useful: