tags:

views:

96

answers:

7

Hello All, How can I escape a ' (single quote) in JS. This is where I'm trying to use it.

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

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

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

How can I successfully escape the single quotes.

A: 

Tryed with & #145; ?

thelost
+1  A: 

Probably the easiest way:

<input type='text' id='abc' value="hel'lo">
hkda150
+5  A: 

First of all, you should use double-quotes, arround your HTML attributes' values :

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


Then, if you need to escape some characters, you could use html entities :

  • &#039; for '
  • &quot; for "
  • ...

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

Pascal MARTIN
Why *should* one use double quotes for attribute values?
Gumbo
aahhhh!!.. Can't I even think of this. Thanks a lot. :)
Ravi
HUmph ; I'm guessing I *should* have said *could*, as it helps, in this specific case, but is not necessarily necessary ;; still, a *(in my opinion)* good reason would be that it's closer to XHTML.
Pascal MARTIN
It's the convention... see: http://www.w3.org/TR/1999/REC-html401-19991224/intro/sgmltut.html#h-3.2.2
hkda150
@Pascal MARTIN: XML does also allow single quotes for attribute values. (See http://www.w3.org/TR/xml/#NT-AttValue)
Gumbo
@Gumbo : wooo ! I don't think I've ever seen any XML document that was using single-quotes arround attributes values ; so I didn't think this was actually valid ;; I just *(once again)* learnt something while answering a question ; so, thanks for those comments !
Pascal MARTIN
+3  A: 

You can use &apos; (which is iffy in IE) or &#39; (which should work everywhere). You can also read about other entities at w3schools.

Benjamin Manns
A: 

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'>
Gumbo
A: 

Represent it as text entity (ASCII 39):

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

Heard of double escaping? My favourite:

var str = "<input type='text' id='abc' value='hel\\\'lo'>";

or

var str = "<input type="text" id="abc" value="hel'lo">';
thephpdeveloper