Javascript and backslashes replace

前端 未结 7 1516
伪装坚强ぢ
伪装坚强ぢ 2020-11-27 07:50

here is my string:

var str = \"This is my \\string\";

This is my code:

var replaced = str.replace(\"/\\\\/\", \"\\\\\\\\\")         


        
7条回答
  •  渐次进展
    2020-11-27 08:51

    The problem is that the \ in your first line isn't even recognized. It thinks the backslash is going to mark an escape sequence, but \s isn't an escape character, so it's ignored. Your var str is interpreted as just "This is my string". Try str.indexOf("\\") - you'll find it's -1, since there is no backslash at all. If you control the content of str, do what David says - add another \ to escape the first.

提交回复
热议问题