How do you use a variable in a regular expression?
Instead of using the /regex/g syntax, you can construct a new RegExp object:
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: