Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/435.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript RegExp函数不能与alternation一起使用_Javascript_Regex_Alternate_Alternating - Fatal编程技术网

Javascript RegExp函数不能与alternation一起使用

Javascript RegExp函数不能与alternation一起使用,javascript,regex,alternate,alternating,Javascript,Regex,Alternate,Alternating,出于某种原因,这不会同时影响后跟空格的过滤器和前面带有空格的过滤器。假设过滤器为“,”,它将采用第二个面,并且只替换“,”而不是“,”和“,”。筛选器是用户指定的,因此我无法使用正常的正则表达式(它确实有效),例如string=string.replace(/,|,/g,filter[a]) 有人能给我解释一下为什么它不起作用以及如何使它起作用吗?它对我起作用: string=string.replace(RegExp(filter[a]+" | "+filter[a],"g"),filter[

出于某种原因,这不会同时影响后跟空格的过滤器和前面带有空格的过滤器。假设过滤器为“,”,它将采用第二个面,并且只替换“,”而不是“,”和“,”。筛选器是用户指定的,因此我无法使用正常的正则表达式(它确实有效),例如
string=string.replace(/,|,/g,filter[a])
有人能给我解释一下为什么它不起作用以及如何使它起作用吗?

它对我起作用:

string=string.replace(RegExp(filter[a]+" | "+filter[a],"g"),filter[a])
请记住,正则表达式不会将“
”、“
替换为“
”、“
”。您可以尝试改用此选项:

s = 'abc, def,ghi ,klm'
a = ','
s = s.replace(RegExp(a + " | " + a, "g"), a)
"abc,def,ghi,klm"

您能否提供一个简短但完整的可运行示例,我们可以使用它来重现您遇到的错误?请确保您引用的所有变量都在示例代码中定义,以便我们可以在不需要修改的情况下运行它。
" ?" + filter[a] + " ?"