Replacing quotes in Javascript?

For the web application that I am creating, I am going to get text strings, sometimes containing quotation marks. Because then I will document. Writing a line, they need to be changed either in apostrophes or with escaping. How would I do this, because when I try to do this, it does not seem to work, in particular, I think, because the string quotes stop the rest of the script from working.

Hope this makes some sense, I'm completely new to this, so why it might not make sense. I will try and clarify if necessary. Thanks!

+7
javascript replace
source share
3 answers

Reset them for HTML:

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

Reset them for JS code:

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

If you generate Javascript strings on the server, you will need to avoid quotes and some other characters.

 \' Single quotation mark \" Double quotation mark \\ Backslash \b Backspace \f Form feed \n New line \r Carriage return \t Horizontal tab \ddd Octal sequence (3 digits: ddd) \xdd Hexadecimal sequence (2 digits: dd) \udddd Unicode sequence (4 hex digits: dddd) 
+10
source share

You need to escape from them like this:

 var foo = '\'foo\''; 

So, if the original string has single quotes, replace each individual quote with a slash and one quote.

+1
source share

All Articles