Advertisement
Advertisement


How do I escape a single quote?


Question

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?

2017/08/28
1
193
8/28/2017 9:22:02 PM

Accepted Answer

You could use HTML entities:

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

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

2017/11/10
367
11/10/2017 8:13:29 PM

You can use &apos; (which is iffy in IE) or &#39; (which should work everywhere). For a comprehensive list, see the W3C HTML5 Named Character References or the HTML entities table on WebPlatform.org.

2013/03/28

As you’re in the context of HTML, you need to use HTML to represent that character. And for HTML you need to use a numeric character reference &#39; (&#x27; hexadecimal):

<input type='text' id='abc' value='hel&#39;lo'>
2010/03/11

Represent it as a text entity (ASCII 39):

<input type='text' id='abc' value='hel&#39;lo'>
2019/08/12

Probably the easiest way:

<input type='text' id='abc' value="hel'lo">
2010/03/11

You could try using: &#145;

2012/11/17

Source: https://stackoverflow.com/questions/2428572
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]