9

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!

2
  • What language are you writing the web app in? Commented Feb 28, 2010 at 15:50
  • @James Please add your example code and error message to the question. Commented Feb 28, 2010 at 16:20

4 Answers 4

20

Escaping them for HTML:

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

Escaping them for JS code:

var escapedString = string.replace(/(['"])/g, "\\$1");
Sign up to request clarification or add additional context in comments.

Comments

11

If you are generating Javascript strings on the server, you will need to escape quotes and certain 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)   

1 Comment

So, if the string has just been generated and I can't change what is generated, how can I then escape all the quotes in that string I guess is my question? Thanks!
2

Try the following code in some HTML:

string.replace(/"/g, '');

If it's just JS you can use:

string.replace(/"/g, '');

This remove de undesired quotes on submited values from user.

Comments

1

You need to escape them like so:

var foo = '\'foo\'';

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.