1

I'm trying to change a string variable 'foo / bar' into 'foo \/ bar' but I keep getting 'foo \\/ bar'. I don't want to hard code it. How is it done?

> fb = 'foo / bar'
'foo / bar'
> fb.replace('/', '\\/')
'foo \\/ bar'
> fb.substr(0, fb.indexOf('/')) + '\\' + fb.substr(fb.indexOf('/'))
'foo \\/ bar'
1
  • try console.log('foo / bar'.replace('/', '\\/')) Commented Apr 7, 2016 at 13:09

1 Answer 1

1

Your replace (fb.replace('/', '\\/')) is correct (if you only want to replace the first one). It's just that whatever console you're using is showing you the string in string literal format, and in a string literal, to actually have a \ in a string, you have to escape it (with another \). Your replaced string actually only has one \ in it, it's just how the console is displaying it to you.

Gratuitous example:

var fb = 'foo / bar';
fb = fb.replace('/', '\\/');
var pre = document.createElement('pre');
pre.appendChild(
  document.createTextNode(fb)
);
document.body.appendChild(pre);


If you want to replace all / in the string (if there were more than one):

var fb = "foo / bar";
fb = fb.replace(/\//g, "\\/");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.