Encode HTML entities with jQuery
Posted on 21/7/07 by Felix Geisendörfer
Hey folks,
just a quick tip, if you ever need to use something like PHP's htmlentities() function in JS and happen to use the excellent jQuery library, here is how to do it:
Enjoy the magic,
-- Felix Geisendörfer aka the_undefined
You can skip to the end and add a comment.
Neat! Thanks a bunch.
what if I need something simple like
htmlEncode('thisdf oeo 3r2o32o3');?
Use the same call he made above, just slam your text or variable in to this text. It will not modify the div in any way, just output data html entity encoded.
Thanks a lot! Helped me fix an issue.
how i will use this progressbar in symfony 1.0
bye
thanks
What is $('<div/>')? Is it some kind of virtual element? I evaluated in firebug console $('<div/>').text('something') and it changes value of div. The question is: What is this div?
Viktar: It's an element not attached to the document tree. Until you attach it to an existing element it pretty much is isolated from anything else.
Thank you. Great post. Now, when you explained, I found documentation about this on jquery web site.
this was a life saver! Thanks!
Looks like this method doesn't work 100% correct in IE (Firefox is fine). I am using this method to encode textarea value. In some cases it replaces \r\n\t with \t\t\t. In other words it replaces new lines characters with tab. So, ended up using this:
function htmlEncode(s) {
var str = new String(s);
str = str.replace(/&/g, "&");
str = str.replace(/
str = str.replace(/>/g, ">");
str = str.replace(/"/g, """);
return str;
}
What if I want to encode the value of an input element?
$('#element_id').val().html() doesn't work.
M:
var str=$('#my_input').val();
$('#element_id').text(str);
The inverse works:
$('<div/>').html('check & see if X<Z...').text();
Be careful using this. Whenever you use jQuery's function .html(val)
with val coming from user input, you will be introducing xss vulnerability as it will be evaluated if there are any script tags.
I'm not totally sure if this function will have issues because you are taking the text element which will encode < from the string, however the reverse function is definitely vulnerable as I am in the process of fixing it for my site.
This post is too old. We do not allow comments here anymore in order to fight spam. If you have real feedback or questions for the post, please contact us.
This was very helpful!! Thanks!! :-)
Sean