How to Encode html entities in javascript

Here is a breakdown to encode html entities in javascript.This will help you understand how HTML entities can be encoded in javascript with ease which you can use as well.

You can use regex to replace any character in a given unicode range with its html entity equivalent. The code would look something like this:

var encodedStr = rawStr.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
   return '&#'+i.charCodeAt(0)+';';
});

This code will replace all characters in the given range (unicode 00A0 – 9999, as well as ampersand, greater & less than) with their html entity equivalents, which is simply &#nnn; where nnn is the unicode value we get from charCodeAt.

See it in action here:

HTML:

<textarea id="inputText"></textarea>
<button id="doIt">do it</button>

<h3>result</h3>
<code id="output"></code>

CSS:

code {
    display:block;
    padding: 4px;
    background-color: #EFEFEF;
    
}

JAVASCRIPT:

$('#doIt').click(function () {
    var encodedStr = $('#inputText').val().replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
       return '&#'+i.charCodeAt(0)+';';
    });
    $('#output').html(encodedStr.replace(/&/gim, '&'));
});

(this example uses jQuery for element selectors used in the example. The base code itself, above, does not use jQuery)

Making these conversions does not solve all the problems — make sure you’re using UTF8 character encoding, make sure your database is storing the strings in UTF8. You still may see instances where the characters do not display correctly, depending on system font configuration and other issues out of your control.

Hope this was helpful:)