// variable == 'REGEX' let variable = 'REGEX'; let re = newRegExp(String.raw`\s${variable}\s`, "g"); let result = "mystring1".replace(re, "newstring"); console.log(result);
2. 处理旧浏览器或 Node.js 环境
在旧浏览器或者 Node.js 环境中,可采用如下方式:
1 2 3 4 5
// variable == 'REGEX' var variable = 'REGEX'; var re = newRegExp("\\s" + variable + "\\s", "g"); var result = "mystring1".replace(re, "newstring"); console.log(result);
let str1 = "."; let re = newRegExp(RegExp.quote(str1), "g"); let result = "pattern matching .".replace(re, "regex"); console.log(result);
4. 利用模板字符串
使用模板字符串能更便捷地插入变量:
1 2 3 4 5
let replaceThis = "John"; let re = newRegExp(`\\b${replaceThis}\\b`, 'gi'); let inputString = "I'm John, or johnny, but I prefer john."; let result = inputString.replace(re, "Jack"); console.log(result);
核心代码
1. 基本的 RegExp 构造函数使用
1 2 3 4
let variable = 'REGEX'; let re = newRegExp(String.raw`\s${variable}\s`, "g"); let result = "mystring1".replace(re, "newstring"); console.log(result);
let replaceThis = "John"; let re = newRegExp(`\\b${replaceThis}\\b`, 'gi'); let inputString = "I'm John, or johnny, but I prefer john."; let result = inputString.replace(re, "Jack"); console.log(result);