views:

165

answers:

5

Just a string. Add \' to it every time there is a single quote.

+2  A: 
var myNewString = myOldString.replace(/'/g, "\\'");
womp
+7  A: 

replace works for the first quote, so you need a tiny regular expression:

str = str.replace(/'/g, "\\'");
Kobi
+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
+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
+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
Those strings are identical. Unless you meant '\\x27'.
Matthew Crumley