Grow your CSS skills. Land your dream job.

Last updated on:

htmlEntities for JavaScript

htmlentities() is a PHP function which converts special characters (like <) into their escaped/encoded values (like &lt;). This allows you to show to display the string without the browser reading it as HTML.

JavaScript doesn't have a native version of it. If you just need the very basics to so that the browser won't interpret as HTML, this should work fine (via James Padolsey and I got a a similar idea from David Walsh).

function htmlEntities(str) {
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

The PHP.js project, which is a project to port over all of PHP's native functions to JavaScript, contains an example as well. I tried it and it works, but I've been warned much of the code from that project is poorly written, so I've kept it simple and used the above.

Comments

  1. Krinkle
    Permalink to comment#

    I use the following two functions, in my opinion a very solid, complete and easy method.
    This particulary example uses jQuery but the principe isn’t dependant on jQuery:

    // Encode/decode htmlentities
    	function krEncodeEntities(s){
    		return $j("<div/>").text(s).html();
    	}
    	function krDencodeEntities(s){
    		return $j("<div/>").html(s).text();
    	}
    • Miguel
      Permalink to comment#

      Can you show an example of the above jquery encoding working on a form?

      Is this right?

    • Thanks a lot haha! It’ll solve a lot of problems with AJAX for me :D

    • HayNar
      Permalink to comment#

      This is nice hack but it’s not useful for high scale web applications where the performance is crucial. This portion of code creates a dummy DOM element to manipulate the text inside, DOM method calls are the most resource taking methods. I would prefer using multiple replaces applied to the string rather than creating and destroying a dummy DOM element.

  2. Permalink to comment#

    Thanks for the two functions, that helped me out of a pickle working with a serialized query string.

  3. Mark
    Permalink to comment#

    Thanks for the info!! (^_^)b

  4. buzz
    Permalink to comment#

    the problem with the jQuery approach is if your text contains htmlentities, e.g.

    $(”).text(‘&’).html()

    outputs:

    “&amp;”

    maybe not what you want…..

    • buzz
      Permalink to comment#

      entities filtered in above post. should read:

      $(‘<p>’).text(‘&amp;’).html()

      will output

      &amp;amp;

  5. Vinay
    Permalink to comment#

    Thanks it helped..:)?

  6. john
    Permalink to comment#

    Sure it works when you post, but what about saving

  7. Bret
    Permalink to comment#

    The problem with this approach, as Buzz alluded to, is that all ampersands, even if already properly html-ized, will be matched, resulting in things like htmlentities("&amp;") == "&amp;amp;" and htmlentities(htmlentities("<")) == "&amp;lt;" (not that you’d do the latter, but just to illustrate the point). You want to pad the ampersand regex. Just a space will work for most cases, i.e.:

    s.replace(/& /g, '&amp; ')

    or you can get fancier with something along the lines of:

    s.replace(/&[^(#\d+;|a-z+;)]/g, '&amp;')
    • James
      Permalink to comment#

      Why not just replace all &amp; with an & as the first replace method? This solves the problem of double-encoding ampersands.

      return String(str).replace(/&amp;/g, '&').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
      

      This works for me quite well.

  8. Jay
    Permalink to comment#

    How does one do the opposite of this? I want to show the interpreted html entity in js. Example:

    
    $(function(){
        $("#demo").formwizard({ 
            textNext: 'Go to step two »'
            }
    );
    
    

    Would like ‘textNext’ to output as Go to step two »

  9. Pimm Hogeling
    Permalink to comment#

    Please note that this doesn’t do the same as the PHP function. The PHP function uses HTML entities; while this function uses XML ones.

    For example, this function leaves Orléans unaltered, while the PHP function turns that string into Orl&eacute;ans.

  10. Shilpa
    Permalink to comment#

    Helped me a lot… krEncodeEntities, krDencodeEntities solved my problem…

  11. KrishnaTorque
    Permalink to comment#

    function htmlEntities(str) {
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g,'&apos');
    }

    Thank you for this script. I have added this .replace(/'/g,'&apos') end of the line. Maybe it will be help

  12. check out this code plz

    $(“body”).text($(“body”).html());

    one line code ;)

  13. The solution Chris posted here works fine.

    However, some of the comments on this page discuss extended implementations that not only escape unsafe characters, but also encode any non-ASCII characters. I just want to say: encoding/decoding HTML entities in JavaScript is harder than it seems.

    Here’s a list of common problems in HTML entity encoding/decoding scripts. All the solutions linked to in the comments have at least one of the issues mentioned there. My he library handles all these things perfectly.

  14. Thirunavukkarasu

    This tricked saved my day! Thanks for the simple solution !

  15. I was going to recommend the excellent he library (written by Mathias Bynens), but I see Mathias already took care of that himself. Unless you’re 100% sure the string you need to encode does not contain any special characters, the he library is the only way to go.

Leave a Comment

Current day month ye@r *

*May or may not contain any actual "CSS" or "Tricks".