This question already has answers here:
JavaScript: A BackSlash as part of the string
                                
                                    (3个答案)
                                
                        
                2年前关闭。
            
        

以下代码有什么问题?

预期输出: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, "@"));

最佳答案

您的初始字符串本身没有反斜杠。要验证,请检查以下代码段:



var str = "substr1\sustr2\substr3"
console.log(str);





您可以通过先转义反斜杠然后将其替换为@来获得您期望的实际输出:



var str = "substr1\\sustr2\\substr3"
console.log(str.replace(/\\/g, "@"));

09-17 20:46