如何在 JavaScript 的正则表达式匹配中放置变量?
你可以使用 match() 传递变量名。语法如下 -
console.log(yourVariableName.match(yourMatchingVariableName));
示例
var senetence = 'My Name is John'; console.log("The actual value="); console.log(senetence); var matchWord = 'John'; console.log("The matching value="); console.log(matchWord); var matchRegularExpression = new RegExp(matchWord, 'g' ); console.log(senetence.match(matchWord));
要运行上面的程序,你需要使用下面的命令 -
node fileName.js.
此处,我的文件名是 demo107.js。
输出
这将产生以下输出 -
PS C:\Users\Amit\JavaScript-code> node demo107.js The actual value= My Name is John The matching value= John
广告