here is my string:
var str = \"This is my \\string\";
This is my code:
var replaced = str.replace(\"/\\\\/\", \"\\\\\\\\\")
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'