我有一些用|
(空格符)隔开的字符串,我想用逗号替换它们。我在下面尝试了此操作,但它给了我一个错误:Uncaught SyntaxError: missing ) after argument list
var string = 'This is my | string I want to replace';
string.replace(' | 'g, '/,/ ');
console.log(string);
// Desired output:
// This is my, string I want to replace
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
答案 0 :(得分:1)
您似乎混淆了很多东西。
如果要使用g
,则应使用正则表达式-显示的内容不是有效的JS:
...replace(/ | /g, '/,/ ')
使用正则表达式后,您需要转义|
:
...replace(/ \| /g, '/,/ ')
然后指定您要替换的字符串,该字符串在代码中以斜杠显示,但不要在文章中提及:
...replace(/ \| /g, ', ')
由于replace
不到位,您需要保存结果:
const s2 = string.replace(/ \| /g, ', ')
// s2 = "This is my, string I want to replace"
有时阅读文档确实对我们有帮助。
(请注意,根据输入的实际情况,您实际上可能想拆分并加入,
。)