rm.rf.etc
rm.rf.etc

Reputation: 922

javascript replace / with \/

I am trying to escape all forward slashes in a string.

objective:

convert('path/to/awesomeness/{plus}/{special-characters!}/')
'path\/to\/awesomeness\/{plus}\/{special-characters!}\/'

result 1:

'path/to/awesomeness/{plus}/{special-characters!}/'.replace(/\//g, '\/')
'path/to/awesomeness/{plus}/{special-characters!}/'

result 2:

'path/to/awesomeness/{plus}/{special-characters!}/'.replace(/\//g, '\\/')
'path\\/to\\/awesomeness\\/{plus}\\/{special-characters!}\\/'

In the node console, it gives the above outputs. Check : https://i.sstatic.net/X471f.png. How can I replace / with \/?

Upvotes: 2

Views: 1317

Answers (1)

Matthew Gilliard
Matthew Gilliard

Reputation: 9498

Your second attempt has actually worked fine. The problem is how to read a string that has escaped characters in it, as shown in the Node console. If you want to put an apostrophe in the middle of a string, you have to escape it like this:

var s = 'I\'m cool';

And in the same way, when you want to put a backslash in a string, you have to escape that, too:

var s = 'This is a single backslash: \\';

So, if you did this: '/'.replace(/\//g, '\\') you'd get a single-character string - a backslash. Node chooses to show you string as you'd have to type it to make it valid in code (ie an escaped backslash, which looks like 2 backslashes), not as it actually is.

The Chrome console does not do this, nor does Firefox. Try it there and see the difference.

Upvotes: 3

Related Questions