PSD to HTML conversion PSD to HTML conversion PSD2HTML.com with over 300 professionals takes the designs to HTML and beyond

Code Snippet

Home » Code Snippets » JavaScript » htmlEntities for JavaScript

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.

Subscribe to The Thread

  1. Krinkle says:

    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 says:

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

      Is this right?

  2. Ben says:

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

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~