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?
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.
Javascript uses '\' (backslash) in front as an escape character.
TypeScript is going to emit the JavaScript the same as it saw it. "/\\" is the JavaScript representation of forwardslash backslash, just as you intend.
The escape() function in JavaScript is used for encoding a string. It is deprecated in JavaScript 1.5.
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.
You can use String.raw to add slashes conveniently into your string literals. E.g. String.raw`\a\bcd\e`.replace(/\\/g, '\');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With