How do I add slashes to a string in Javascript?

Viewed 141049

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

8 Answers

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

str = str.replace(/'/g, "\\'");

To be sure, you need to not only replace the single quotes, but as well the already escaped ones:

"first ' and \' second".replace(/'|\\'/g, "\\'")

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.

var myNewString = myOldString.replace(/'/g, "\\'");
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: \'
Related