Szymon Toda
Szymon Toda

Reputation: 4516

How to escape backslash in JavaScript?

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?

Upvotes: 15

Views: 44983

Answers (2)

Tamas Rev
Tamas Rev

Reputation: 7166

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

Upvotes: 4

dansch
dansch

Reputation: 6267

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.

Upvotes: 19

Related Questions