Javascript Regexp dynamic generation from variables?
This question already has an answer here:
You have to use RegExp
:
str.match(new RegExp(pattern1+'|'+pattern2, 'gi'));
When I'm concatenating strings, all slashes are gone.
If you have a backslash in your pattern to escape a special regex character, (like (
), you have to use two backslashes in the string (because is the escape character in a string):
new RegExp('(')
would be the same as /(/
.
So your patterns have to become:
var pattern1 = ':(|:=(|:-(';
var pattern2 = ':(|:=(|:-(|:(|:=(|:-(';
使用以下内容:
var regEx = new RegExp(pattern1+'|'+pattern2, 'gi');
str.match(regEx);
您必须放弃正则表达式并使用对象构造函数,您可以将正则表达式作为字符串传递。
var regex = new RegExp(pattern1+'|'+pattern2, 'gi');
str.match(regex);
链接地址: http://www.djcxy.com/p/76820.html
上一篇: JS使用变量替换所有出现的字符串