1

How do I escape backslash in java script . This is what I need: ( tried from browser developer console)

var str = 'this is \\ test';
console.log(str);

This works fine and prints: this is \ test

How do I do the same using replace function . Basically the above hard code (\) works . I want to have a generic solution for any string .

I tried below:

var str = 'this is \ test';
str=str.replace(/\\/g, "\\\\");
console.log(str);

but it just prints : this is test

My end goal is to pass a string with backslash in a REST Json Body . However it fails with HTTP 400 bad request . So I am looking to escape the backslash before i pass it on to the Json body

So I am looking for a code to replace \ with \

  • Do you have single backslash or double backslash in `str`? As you have specified `var str = 'this is \ test';` and `var str = 'this is \\ test';`. Both re different. – Ankit Agarwal Feb 03 '18 at 06:05
  • 1
    Possible duplicate of [How to replace all occurrences of a string in JavaScript?](https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string-in-javascript) – Rushil K. Pachchigar Feb 03 '18 at 06:09
  • When you declare `var str = 'this is \ test';` `\ ` gets converted to ` ` at declaration, and it's too late to try any conversion from js execution. You would have to handle it from your code directly. – Kaiido Feb 03 '18 at 09:53

1 Answers1

0

When you log the str you will see that there is no \ in the actual string. It's just white space. I believe it is not possible replace something which is not even in the string.

var str = 'this is \ test';
console.log(str);
vatz88
  • 2,422
  • 2
  • 14
  • 25
  • 1
    What you are replacing here is two consecutive space characters, not \ – Kaiido Feb 03 '18 at 09:59
  • 1
    @Kaiido Thanks. I changed the answser. The backslash `\\` doesn't exist in the string so no point in trying to replace it. – vatz88 Feb 03 '18 at 10:09