Javascript 如何使用字符串文本生成regExp?
我试图在ES6中创建一个带有字符串文字的正则表达式,但我的解决方案失败了:Javascript 如何使用字符串文本生成regExp?,javascript,regex,ecmascript-6,Javascript,Regex,Ecmascript 6,我试图在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); 您需要使用n
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);
您需要使用
newregexp
var前缀='Hello';
var reStr=`${prefix}\\s(\\w+)\\s(\\w+)`;
var re=新的RegExp(rest,'g')
var str='你好,约翰·史密斯';
var newstr=str.replace(关于“$2,$1”);
console.log(newstr)代码>您需要使用新的RegExp
var前缀='Hello';
var reStr=`${prefix}\\s(\\w+)\\s(\\w+)`;
var re=新的RegExp(rest,'g')
var str='你好,约翰·史密斯';
var newstr=str.replace(关于“$2,$1”);
console.log(newstr)代码>只能在模板文本中使用${..}
。如果要使用模板文字,请将其传递给newregexp
。为什么这个问题被否决?很明显,他想要实现的目标是什么,而解决方案却并非如此trivial@Phil这个问题不是重复的,引用的问题使用变量,这里是字符串文本used@colxi我真的不认为这有什么区别。此外,使用字符串文字您只能在模板文字中使用${..}
。如果要使用模板文字,请将其传递给newregexp
。为什么这个问题被否决?很明显,他想要实现的目标是什么,而解决方案却并非如此trivial@Phil这个问题不是重复的,引用的问题使用变量,这里是字符串文本used@colxi我真的不认为这有什么区别。此外,还使用字符串文本