Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 887
Szymon Toda Avatar asked Oct 12 '12 20:10

Szymon Toda


People also ask

How do I escape a backslash?

The first two backslashes ( \\ ) indicate that you are escaping a single backslash character. The third backslash indicates that you are escaping the double-quote that is part of the string to match.

How do you escape a slash in JavaScript?

Javascript uses '\' (backslash) in front as an escape character.

How do you escape a backslash in TypeScript?

TypeScript is going to emit the JavaScript the same as it saw it. "/\\" is the JavaScript representation of forwardslash backslash, just as you intend.

What is escape () in JS?

The escape() function in JavaScript is used for encoding a string. It is deprecated in JavaScript 1.5.


2 Answers

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.

like image 114
dansch Avatar answered Oct 20 '22 22:10

dansch


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

like image 36
Tamas Rev Avatar answered Oct 20 '22 23:10

Tamas Rev