Encode HTML entities with jQuery

Posted by Felix Geisendörfer, on Jul 21, 2007 - in JavaScript & jQuery

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:

javascript
  1. $('<div/>').text('This is fun & stuff').html(); // evaluates to "This is fun &amp; stuff"

Enjoy the magic,
-- Felix Geisendörfer aka the_undefined

Print this Post | Digg This | Stumble It | Delicious

8 Comments

SeanG on Aug 06, 2007:

This was very helpful!! Thanks!! :-)

Sean

trice22 on Jul 04, 2008:

Neat! Thanks a bunch.

wt? on Jul 14, 2008:

what if I need something simple like

htmlEncode('thisdf oeo 3r2o32o3');?

Jim on Jul 29, 2008:

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.

Henrik N on Sep 24, 2008:

Thanks a lot! Helped me fix an issue.

sandip on Oct 01, 2008:

how i will use this progressbar in symfony 1.0

bye
thanks

Viktar 1 hour, 32 minutes ago:

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?

Felix Geisendörfer 1 hour, 15 minutes ago:

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.

Add a comment