0

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
TadejP
  • 912
  • 11
  • 21
  • 3
    Log the value of `s` before you try to do anything with it. You only have one backslash in it in the first place. – Quentin Jan 08 '18 at 21:17
  • 1
    Possible duplicate of [Javascript and backslashes replace](https://stackoverflow.com/questions/2479309/javascript-and-backslashes-replace) – luisenrike Jan 08 '18 at 21:24

1 Answers1

0

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'
Phillip Thomas
  • 1,450
  • 11
  • 21