[英]Javascript regex pattern array with loop
I have attempted to create a function that will replace multiple regular expression values from an array. 我试图创建一个函数来替换数组中的多个正则表达式值。 This works if the array does not contain quotation marks of any kind, this is problematic when I want to use a comma in my pattern.
如果数组不包含任何引号,则此方法有效,当我要在模式中使用逗号时,这会出现问题。 So I've been trying to find an alternative way of serving the pattern with no luck.
因此,我一直在尝试寻找一种没有运气的替代方式。 Any ideas?
有任何想法吗?
function removeCharacters(str){
//ucpa = unwanted character pattern array
//var ucpa = [/{/g,/}/g,/--/g,/---/g,/-/g,/^.\s/];
var ucpa = ["/{/","/}/","/--/","/---/","/-/","/^.\s/","/^,\s/"];
for (var i = 0; i < ucpa.length; i++){
//does not work
var pattern = new RegExp(ucpa[i],"g");
var str = str.replace(pattern, " ");
}
return str;
}
WORKING: 工作:
function removeCharacters(str){
//ucpa = unwanted character pattern array
var ucpa = [/{/g,/}/g,/--/g,/---/g,/-/g,/^.\s/,/^,\s/];
for (var i = 0; i < ucpa.length; i++){
var str = str.replace(ucpa[i], " ");
}
return str;
}
REFINED: 精制:
function removeCharacters(str){
var pattern = /[{}]|-{1,3}|^[.,]\s/g;
str = str.replace(pattern, " ");
return str;
}
The RegExp
constructor takes raw expressions, not wrapped in /
characters. RegExp
构造函数采用原始表达式,而不用/
字符包装。 Therefore, all of your regexes contain two /
s each, which isn't what you want. 因此,您所有的正则表达式都包含两个
/
s,这不是您想要的。
Instead, you should make an array of actual regex literals: 相反,您应该制作一个实际的正则表达式文字数组:
var ucpa = [ /.../g, /",\/.../g, ... ];
You can also wrap all that into a single regex: 您还可以将所有内容包装到单个正则表达式中:
var str = str.replace(/[{}]|-{1,3}|^[.,]\s/g, " ")
although I'm not sure if that's exactly what you want since some of your regexes are nonsensical, for example ,^\\s
could never match. 尽管由于某些正则表达式是荒谬的,所以我不确定这是否正是您想要的,例如
,^\\s
永远无法匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.