I am having a problem trying to replace the backslash character from a string:
var g = myReadString;
g = g.replace("\", "\\\\");
it is giving an error of unrecognized character.
How could a simple \
be replaced with four \\\\
?
I would appreciate any help, thanks. Pandy
Javascript uses '\' (backslash) in front as an escape character. To print quotes, using escape characters we have two options: For single quotes: \' (backslash followed by single quote) For double quotes: \” (backslash followed by double quotes)
The backslash() is an escape character in JavaScript. The backslash \ is reserved for use as an escape character in JavaScript. To escape the backslash in JavaScript use two backslashes.
The \
is the begin of an escape sequence. If you mean to write \
literally, you need to write \\
that is an escape sequence as well and will be interpreted as a single \
. So if you want to replace one \
by four \\\\
, you need to write this:
g.replace("\\", "\\\\\\\\")
But this will only replace the first occurrence of a single \
. To do a global replace you need to use a regular expression with the global match modifier:
g.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