为什么 JS 中的字符串替换不替换所有字符

Why string replace in JS doesn't replace all characters

"-x-x+x".replace('-', '+')

等于

"+x-x+x"

为什么不替换第二个 -

.replace 仅替换它找到的第一个实例。要替换所有这些,请使用正则表达式:

"-x-x+x".replace(/-/g, '+')

注意正则表达式末尾的 /g:它表示 "global" 模式。没有它,您仍然只能替换第一个实例。

将其转换为正则表达式以替换所有内容。

console.log("-x-x+x".replace(/-/g, '+'))

这在 String#replace 的文档中有解释:

使用正则表达式:

'-x-x+x'.replace(/-/g, '+')
//=> "+x+x+x"