Just a string. Add \' to it every time there is a single quote.
+7
A:
replace
works for the first quote, so you need a tiny regular expression:
str = str.replace(/'/g, "\\'");
Kobi
2010-02-03 21:26:29
+1
A:
var str = "This is a single quote: ' and so is this: '";
console.log(str);
var replaced = str.replace(/'/g, "\\'");
console.log(replaced);
Gives you:
This is a single quote: ' and so is this: '
This is a single quote: \' and so is this: \'
Vivin Paliath
2010-02-03 21:27:09
+1
A:
To be sure, you need to not only replace the single quotes, but as well the already escaped ones:
"first ' and \' second".replace(/'|\\'/g, "\\'")
Mic
2010-02-03 21:32:42
+1
A:
An answer you didn't ask for that may be helpful, if you're doing the replacement in preparation for sending the string into alert() -- or anything else where a single quote character might trip you up.
str.replace("'",'\x27')
That will replace all single quotes with the hex code for single quote.
lance
2010-02-03 21:59:34
Those strings are identical. Unless you meant '\\x27'.
Matthew Crumley
2010-02-03 23:28:55