如何使用字符串文字生成regExp?

时间:2018-08-03 03:00:07

标签: javascript regex ecmascript-6

我正在尝试在ES6中使用String Literal创建一个正则表达式,但是我的解决方案失败了:

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);

1 个答案:

答案 0 :(得分:3)

您需要使用new RegExp

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);