Home >Web Front-end >JS Tutorial >How Can I Use Variables in Regular Expressions with JavaScript's `replaceAll` Method?
Utilizing Variables in Regular Expressions for JavaScript's ReplaceAll Method
The String.replaceAll() method provides a concise solution for replacing substrings within a string. However, integrating variables into a regular expression can present a challenge.
To resolve this issue, consider constructing a RegExp object dynamically instead of using the traditional /sREGEXs/g syntax. Using String.raw`` ensures that any special characters within the variable remain intact.
const variable = 'REGEX'; const re = new RegExp(String.raw`\s${variable}\s`, "g");
This approach grants flexibility in dynamically creating regex objects based on your requirements. Subsequently, you can employ the replace() method to perform the desired replacements.
"mystring1".replace(re, "newstring");
Note for Older Browsers or Node.js:
For older browsers or Node.js versions, you can use the following syntax:
const re = new RegExp("\s" + variable + "\s", "g"); "mystring1".replace(re, "newstring");
The above is the detailed content of How Can I Use Variables in Regular Expressions with JavaScript's `replaceAll` Method?. For more information, please follow other related articles on the PHP Chinese website!