Ravi
Ravi

Reputation: 8209

How can I escape a single quote?

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

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?

Upvotes: 242

Views: 411831

Answers (9)

Flimm
Flimm

Reputation: 150643

I personally find the named HTML entities easier to remember:

  • &apos; for ' (known as single quote or apostrophe, Unicode character U+0027)
  • &quot; for " (known as double quote or quotation mark, Unicode character U+0022)

Demo:

&apos;
<br>
&quot;

Upvotes: 1

Picard
Picard

Reputation: 4102

If for some reason you cannot escape the apostrophe character and you can't change it into a HTML entity (as it was in my case for a specific Vue.js property) you can use replace to change it into different apostrophe character from the UTF-8 characters set, for instance:

ʼ - U+02BC
’ - U+2019

Upvotes: 0

Ram Bharlia
Ram Bharlia

Reputation: 62

use javascript inbuild functions escape and unescape

for example

var escapedData = escape("hel'lo");   
output = "%27hel%27lo%27" which can be used in the attribute.

again to read the value from the attr

var unescapedData = unescape("%27hel%27lo%27")
output = "'hel'lo'"

This will be helpful if you have huge json stringify data to be used in the attribute

Upvotes: -2

AndiDog
AndiDog

Reputation: 70158

Represent it as a text entity (ASCII 39):

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

Upvotes: 8

Pascal MARTIN
Pascal MARTIN

Reputation: 401002

You could use HTML entities:

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

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

Upvotes: 433

Benjamin Manns
Benjamin Manns

Reputation: 9148

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.

Upvotes: 77

thelost
thelost

Reputation: 6694

You could try using: &#145;

Upvotes: -1

Gumbo
Gumbo

Reputation: 655239

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'>

Upvotes: 10

road242
road242

Reputation: 2532

Probably the easiest way:

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

Upvotes: 6

Related Questions