简体   繁体   中英

How to replace single backslash with double backslash in Javascript

I have seen a lot of duplicates but none of them works

I spend a day to get this thing up. Gone through all duplicates

I need to replace a single backslash with a double backslash.

I am able to replace all other characters with a double backslash.

 console.log("hello & 100\\|".replace(/([&%$#_{}])/g, "\\\\"));

I know that two backslashes is indeed used to make a single backslash.

I tried all the possible ways of using regex as well. But neither works.

Here is another snippet I am using.

 var replaceableString = "A\\B"; replaceableString = replaceableString.replace(/\\\\/g, "\\\\\\\\"); console.log(replaceableString);

Unfortunately, this also is not working.

Please share if there are any workarounds.

var str = "AAA\\BBB\\CCC\\DDD\\EEE";
var rgx = /\\/g;
var res = str.replace(rgx, "\\\\");
console.log(res);

Comments below questions are very revealing. Single backslash \\ is escape character. To obtain single backslash we must use double backslashes. So we must use four backslashes(in reality double) for replace the backslash.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM