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?
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 UTF8 characters set, for instance:
' - U+02BC
’ - U+2019
Probably the easiest way:
<input type='text' id='abc' value="hel'lo">
You can use '
(which is iffy in IE) or '
(which should work everywhere). For a comprehensive list, see the W3C HTML5 Named Character References or the HTML entities table on WebPlatform.org.
Represent it as a text entity (ASCII 39):
<input type='text' id='abc' value='hel'lo'>
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
You could try using: ‘
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 '
('
hexadecimal):
<input type='text' id='abc' value='hel'lo'>
Source: Stackoverflow.com