15
votes

I want to replace backslash => '\' with secure \ replacement.

But my code replacing all '#' fails when applied for replacing '\':

el = el.replace(/\#/g, '#'); // replaces all '#' //that's cool
el = el.replace(/\\/g, '\'); // replaces all '\' //that's failing

Why?

2
The code you posted works just fine. Are you sure that el contains '\' characters?zzzzBov
Can you give us a test case where it is failing, seems to work for me on a simple test case.Akshet
Hmm take a look: pastebin.com/t27vmCzsSzymon Toda
In that script you already use encodeURIComponent() which replaces any backslashes with %5C. I think you don't need the two manual replacements.Wolfgang Stengel
FYI # doesn't need to be escaped; el.replace(/#/g, '#') should work. And also your code to replace backslashes works fine here.NullUserException

2 Answers

14
votes

open console and type

'\'.replace(/\\/g, '\'); 

fails because the slash in the string isn't really in the string, it's escaping '

'\\'.replace(/\\/g, '\');

works because it takes one slash and finds it.

your regex works.

2
votes

You can use String.raw to add slashes conveniently into your string literals. E.g. String.raw`\a\bcd\e`.replace(/\\/g, '\');