0

if, a = "Bob\'s house"

how would you replace the backslash with another '? I want a to equal "Bob''s house"

I would assume that I can do a.replace("\", "'") but this doesn't work

Eric Chu
  • 1,649
  • 3
  • 20
  • 26
  • 1
    a.replace("\\", "'") - you need two backslashes – user2182349 Jun 04 '17 at 23:05
  • Press [F12], enter `"Bob\'s house"` into the console and inspect the result - there is no "\" <-- this is an escape character. If you would define `a = "Bob\\'s house"`, then it would work. But this seems somewhat nonsensical to me. How about `a.replace("'", "''")`? – le_m Jun 04 '17 at 23:06
  • See https://stackoverflow.com/questions/2479309/javascript-and-backslashes-replace – le_m Jun 04 '17 at 23:09

3 Answers3

0

It does not work because \' is treated as a single character. In Javascript \ is used to initiate an escape character, which means "literally the character after \".

In order to show \ you therefore need to write \\. And if you want to change escaped ' into '' what you need to do is simply a.replace("\'", "\'\'");

Tukan
  • 2,253
  • 15
  • 17
0

basically a = "Bob\'s house" is interpreted as "Bob's house", youre just escaping the '. there is no backslash in the string.

to have your wanted result ("Bob''s house"), simply do the following:

a.replace("\'", "\'\'")
Bamieh
  • 10,358
  • 4
  • 31
  • 52
0

as user2182349 said, a.repalce("\\", "'") did the trick

Eric Chu
  • 1,649
  • 3
  • 20
  • 26