我正在尝试在 ES6 中使用字符串文字创建正则表达式,但我的解决方案失败了:
var prefix = 'Hello';
var re = /`${prefix}\\s(\\w+)\\s(\\w+)`/;
//var re = /Hello\s(\w+)\s(\w+)/; // this works
var str = 'Hello John Smith';
var newstr = str.replace(re, '$2, $1');
console.log(newstr);
最佳答案
您需要使用新的正则表达式
var prefix = 'Hello';
var reStr = `${prefix}\\s(\\w+)\\s(\\w+)`;
var re = new RegExp(reStr,'g')
var str = 'Hello John Smith';
var newstr = str.replace(re, '$2, $1');
console.log(newstr);
关于javascript - 如何使用字符串文字生成正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51664713/