简体   繁体   中英

How to replace backslashes in node string replace

Simple code, in node v.9.30 i can not replace all occurrences of '\\' to get string "n_fdsan__xsa". Should I use different approach?

s = 'n\fdsan\\xsa';
r = s.replace(/\\\\/g,  "_");
console.log(r);

EDIT: Thanks to @Quentin and @Phillip, I realized that '\\f' is different char - form feed and second one is really backslash - '\\'.

s = 'n\fdsan\\xsa';
r = s.replace(/\\/g,  "_");
console.log(r); 

//   Displays:
n
 dsan_xsa

The issue seems to be the string that is stored is n\\fdsan\\\\xsa which equates to n\\\\fdsan\\\\\\\\xsa when instantiating the js variable. Once the variable is logged you see the expected n\\fdsan\\\\xsa .

In order to replace all instances of a slash character you would use the following:

 s = "n\\\\fdsan\\\\\\\\xsa"; console.log(s); // Displays 'n\\fdsan\\\\xsa' s = s.replace(/\\\\/g, "_"); console.log(s); // Displays 'n_fdsan__xsa' 

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