Javascript and backslashes replace

血红的双手。 提交于 2019-11-26 20:57:47
thegajman

Got stumped by this for ages and all the answers kept insisting that the source string needs to already have escaped backslashes in it ... which isn't always the case.

Do this ..

var replaced = str.replace(String.fromCharCode(92),String.fromCharCode(92,92));

The string doesn't contain a backslash, it contains the \s escape sequence.

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

And if you want a regular expression, you should have a regular expression, not a string.

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

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.

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' 

In case you have multiple instances or the backslash:

str.split(String.fromCharCode(92)).join(String.fromCharCode(92,92))

I haven't tried this, but the following should work

var replaced = str.replace((new RegExp("\s"),"\\s");

Essentially you don't want to replace "\", you want to replace the character represented by the "\s" escape sequence.

Unfortunately you're going to need to do this for every letter of the alphabet, every number, symbol, etc in order to cover all bases

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!