15

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?

5
  • The code you posted works just fine. Are you sure that el contains '\' characters? Commented Oct 12, 2012 at 20:18
  • Can you give us a test case where it is failing, seems to work for me on a simple test case. Commented Oct 12, 2012 at 20:20
  • Hmm take a look: pastebin.com/t27vmCzs Commented Oct 12, 2012 at 20:21
  • 1
    In that script you already use encodeURIComponent() which replaces any backslashes with %5C. I think you don't need the two manual replacements. Commented Oct 12, 2012 at 20:28
  • 1
    FYI # doesn't need to be escaped; el.replace(/#/g, '#') should work. And also your code to replace backslashes works fine here. Commented Oct 12, 2012 at 21:04

2 Answers 2

19

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.

Sign up to request clarification or add additional context in comments.

2 Comments

so how do you handle "domain\user" then? you got to first replace single backslash to double and then use .replace(/\\/g, '\'); ?
/\\/g looks for a single backslash. At no point are we replacing a single with a double. The first backslash escapes the second one, so this regex looks for a single backslash, globally. to handle "domain\user", /\\/g should work fine.
4

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

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.