-1

I'm trying to do a simple replace of a backslash occurence in a string. So I used the string.replace method, passing in a regex for the backslash to be removed \.

But I noticed when I invoke this method, instead of replacing the backslash after EMEA with a colon : character. It just removes the first letter in the username.

I've made a JSFIddle of the code here.

Not sure why the regex doesn't work as it's suggested in other SO answers here:

Replace all backslashes in a string with a pipe

Question:

How can you replace a backslash character with a semicolon?

Code gist:

var str = "EMEA\victorb";
str = str.replace(/\\/g, ':');

document.write(str);
Community
  • 1
  • 1
Brian Var
  • 6,029
  • 25
  • 114
  • 212

2 Answers2

3

That's a problem with the original string, not with the regex: it's

var str = "EMEA\victorb";

When it shold be:

var str = "EMEA\\victorb";
Haroldo_OK
  • 6,612
  • 3
  • 43
  • 80
  • The original string that is returned from the API is including only one backslash. Is there no way to replace an occurrence of one backslash? – Brian Var Oct 27 '16 at 10:57
  • 1
    If the api is returning a backslash it would be automatically encoded into the string. The double backslash is only so that string constants can be encoded. Try your replace method on the actual API data and see what it does. – creeperdomain Oct 27 '16 at 10:59
  • 1
    Ah ok it is double backslashed as you said. Tried it with the live API. – Brian Var Oct 27 '16 at 11:04
0
var str = "EMEA\\victorb";
    str = str.replace("\\", ':'); because if you let just one \ it will be ignored.
SIE
  • 155
  • 1
  • 3