I’m using JavaScript to pull a value out from a hidden field and display it in a textbox. The value in the hidden field is encoded.
For example,
<input id='hiddenId' type='hidden' value='chalk & cheese' />
gets pulled into
<input type='text' value='chalk & cheese' />
via some jQuery to get the value from the hidden field (it’s at this point that I lose the encoding):
$('#hiddenId').attr('value')
The problem is that when I read chalk & cheese
from the hidden field, JavaScript seems to lose the encoding. To escape "
and '
, I want the encoding to remain.
Is there a JavaScript library or a jQuery method that will HTML-encode a string?
Using some of the other answers here I made a version that replaces all the pertinent characters in one pass irrespective of the number of distinct encoded characters (only one call to
replace()
) so will be faster for larger strings.It doesn't rely on the DOM API to exist or on other libraries.
Having ran that once, you can now call
To get
<>&"'
Underscore provides
_.escape()
and_.unescape()
methods that do this.You shouldn't have to escape/encode values in order to shuttle them from one input field to another.
JS doesn't go inserting raw HTML or anything; it just tells the DOM to set the
value
property (or attribute; not sure). Either way, the DOM handles any encoding issues for you. Unless you're doing something odd like usingdocument.write
oreval
, HTML-encoding will be effectively transparent.If you're talking about generating a new textbox to hold the result...it's still as easy. Just pass the static part of the HTML to jQuery, and then set the rest of the properties/attributes on the object it returns to you.
Here's a little bit that emulates the
Server.HTMLEncode
function from Microsoft's ASP, written in pure JavaScript:The result does not encode apostrophes, but encodes the other HTML specials and any character outside the 0x20-0x7e range.
For those who prefer plain javascript, here is the method I have used successfully:
Will output:
<script>alert("I hack your site")</script>
.htmlEncode() will be accessible on all strings once defined.