Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.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 当与string而不是regex一起使用时,replace()不考虑“g”标志_Javascript_String_Replace - Fatal编程技术网

Javascript 当与string而不是regex一起使用时,replace()不考虑“g”标志

Javascript 当与string而不是regex一起使用时,replace()不考虑“g”标志,javascript,string,replace,Javascript,String,Replace,在chrome上,它仅替换|的第一个匹配项,而在replace函数的正则表达式形式中使用g标志时,它替换所有匹配项: var a = 'Construction,Airports,Construction|Commercial Construction,Construction|Education,Construction|Healthcare,Construction|Housing,Construction|Industrial Construction,Construction|Other

在chrome上,它仅替换|的第一个匹配项,而在replace函数的正则表达式形式中使用g标志时,它替换所有匹配项:

var a = 'Construction,Airports,Construction|Commercial Construction,Construction|Education,Construction|Healthcare,Construction|Housing,Construction|Industrial Construction,Construction|Other,Construction|Ports,Construction|Rail,Construction|Residential Construction,Construction|Roads & Bridges,Social Infrastructure|Commercial Construction,Social Infrastructure|Education,Social Infrastructure|Healthcare,Social Infrastructure|Housing,Social Infrastructure|Other,Social Infrastructure|Residential Construction';

alert(a.replace('|', ',', 'g'));
有人能帮我理解我在第一种形式的替换中是否做错了什么吗?这是预期的行为还是bug?

使用flags参数;使用带有相应标志的RegExp对象是标准用法

一些浏览器可能支持字符串版本的标志,但是不应该依赖它

例如,您的示例在Firefox中运行良好,但在Chrome中运行不好

参考:

使用flags参数;使用带有相应标志的RegExp对象是标准用法

一些浏览器可能支持字符串版本的标志,但是不应该依赖它

例如,您的示例在Firefox中运行良好,但在Chrome中运行不好

参考资料:

使用以下格式:a.replace/\\\\124;/g','

根据:

String.replace方法中flags参数的使用是 非标准的不要使用此参数,而是使用RegExp对象 使用相应的标志

使用以下格式:a.replace/\|/g,,'

根据:

String.replace方法中flags参数的使用是 非标准的不要使用此参数,而是使用RegExp对象 使用相应的标志

str.splitsearch.joinreplace是全局替换子字符串的标准技巧。str.splitsearch.joinreplace是全局替换子字符串的标准技巧。
alert(a.replace(/\|/g, ',', 'g'));