以下代码有什么问题?
预期输出: substr1 @ substr2 @ substr3
var str = "substr1\substr2\substr3"
// it works if I use the double slash "\\" in thestring but not with single.
console.log(str.replace(/\\/g, "@"));

答案 0 :(得分:4)
您的初始字符串本身没有反斜杠。要验证检查以下代码段:
var str = "substr1\sustr2\substr3"
console.log(str);

您可以通过首先转义反斜杠然后将其替换为@
来获得您期望的实际输出:
var str = "substr1\\sustr2\\substr3"
console.log(str.replace(/\\/g, "@"));