How do I escape a single quote?

Ravi picture Ravi · Mar 11, 2010 · Viewed 320.3k times · Source

How can I escape a ' (single quote) in JavaScript?

This is where I'm trying to use it:

<input type='text' id='abc' value='hel'lo'>

The result for the above code is "hel" populated in the text box. I tried to replace ' with \', but this what I'm getting.

<input type='text' id='abc' value='hel\'lo'>

The result for the above code is "hel\" populated in the text box.

How can I successfully escape the single quotes?

Answer

Pascal MARTIN picture Pascal MARTIN · Mar 11, 2010

You could use HTML entities:

  • &#39; for '
  • &#34; for "
  • ...

For more, you can take a look at Character entity references in HTML.