Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery- backslash character

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

like image 915
Samuel Beckett Avatar asked Dec 01 '10 13:12

Samuel Beckett


People also ask

How to use escape characters in js?

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)

How do you escape a backslash in JavaScript?

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.


1 Answers

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, "\\\\\\\\")
like image 182
Gumbo Avatar answered Oct 01 '22 21:10

Gumbo