Passing Variables into Regular Expressions for String Replacement in JavaScript
When attempting to create a String.replaceAll() method using regular expressions, one may encounter difficulties in passing variables into the regex. To overcome this challenge, it is essential to understand the correct syntax.
Creating a Dynamic Regular Expression
Instead of using the conventional /sREGEXs/g syntax, create a new RegExp object as follows:
// variable == 'REGEX' let re = new RegExp(String.raw`\s${variable}\s`, "g");
Using the Regex Object
Once the regex object is constructed, you can use it to replace the desired string:
"mystring1".replace(re, "newstring");
Note for Older Browsers or Node
For older browsers or Node.js versions, you can use the following syntax:
// variable == 'REGEX' var re = new RegExp("\s" + variable + "\s", "g"); "mystring1".replace(re, "newstring");
By following these instructions, you can effectively pass variables into regular expressions and perform string replacements in JavaScript.
The above is the detailed content of How to Pass Variables into JavaScript Regular Expressions for String Replacement?. For more information, please follow other related articles on the PHP Chinese website!