How do replace backslash double quote (e.g. \") in a string?
The code below does not work.
<!DOCTYPE html>
<html>
<head>
</head>
<script type="text/javascript">
var myVar = '\"Things You Should Know\"';
document.write(myVar.replace(/\\\"/g, '|'));
</script>
<body>
<br>hello
</body>
</html>
How do replace backslash double quote (e.g. \") in a string?
The code below does not work.
<!DOCTYPE html>
<html>
<head>
</head>
<script type="text/javascript">
var myVar = '\"Things You Should Know\"';
document.write(myVar.replace(/\\\"/g, '|'));
</script>
<body>
<br>hello
</body>
</html>
Share
Improve this question
asked Sep 4, 2013 at 19:43
rayray
8,6998 gold badges46 silver badges58 bronze badges
2
|
5 Answers
Reset to default 8var myVar = '\"Things You Should Know\"';
document.write(myVar.replace(/\"/g, '|'));
The \
escapes the next character so your string only reads "Things You Should Know"
Your string doesn't have the sequence backslash double-quote in it. The backslash is an escape character so \"
means "
(this is useful in strings that are delimited by double quote characters).
If you did have that sequence in your string (by escaping the backslash characters):
var myVar = '\\"Things You Should Know\\"';
… then you could do it with:
var modifiedString = myVar.replace(/\\"/g, "|");
myVar.replace(/\\"/g, '|');
Also, that string you provided didn't have a backslash then a double-quote, it just had a double quote. You escaped the double-quote for nothing.
Here is working Fiddle
var myVar = '\"Things You Should Know\"';
var myVar1 = myVar.replace(/\"/g, '|');
alert(myVar1);
Your variable has no backslashes. \"
in a string puts a quote character in the string. Example:
alert('\"Things You Should Know\"');
brings up a window that says
"Things You Should Know"
/"/g
– Denys Séguret Commented Sep 4, 2013 at 19:46