Javascript and backslashes replace

前端 未结 7 1517
伪装坚强ぢ
伪装坚强ぢ 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:40

    Use this

    str.replace(/(\s)/g,function($0){return $0==' '?' ':'\\s'})
    

    or

    str.replace(/ /g,'something').replace(/\s/g,'\\s').replace(/something/g,' ');
    

    'something' it may be a combination of characters that is not in string

    var str=' \s';  
      str.replace(/\s/g,'\\s'); 
    // return '\\s\\s'   
      str.replace(/ /g,'SpAcE').replace(/\s/g,'\\s').replace(/SpAcE/g,' ');
    // return ' \\s' 
    

提交回复
热议问题