Replacing quotation marks in Javascript?

James Wanchai picture James Wanchai · Feb 28, 2010 · Viewed 38.4k times · Source

For a web app I'm making, I'm going to be getting text strings coming in, occasionally which contain quotation marks. Because I am then going to be document.writing the string, they need to be changed either into apostrophes or escaped. How would I do that, because when I try it doesn't seem to work, specifically I think because the string's quotation marks stop the rest of the script working.

Hope that makes some sense, I'm quite new to this so that's why it might not make sense. I'll try and clarify if need be. Thank you!

Answer

Eli Grey picture Eli Grey · Feb 28, 2010

Escaping them for HTML:

var escapedString = string.replace(/'/g, "'").replace(/"/g, """);

Escaping them for JS code:

var escapedString = string.replace(/(['"])/g, "\\$1");