Home > Web Front-end > JS Tutorial > How to Pass Variables into JavaScript Regular Expressions for String Replacement?

How to Pass Variables into JavaScript Regular Expressions for String Replacement?

DDD
Release: 2025-01-03 17:12:40
Original
359 people have browsed it

How to Pass Variables into JavaScript Regular Expressions for String Replacement?

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");
Copy after login

Using the Regex Object

Once the regex object is constructed, you can use it to replace the desired string:

"mystring1".replace(re, "newstring");
Copy after login

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");
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template