Today I wanted to use the htmlentities-function in JavaScript. This useful function is available for PHP but it’s not for JavaScript. The reason why I needed the htmlentities-function was the use of the element property innerHTML. I wanted to insert contents into a div container and output some JavaScript variables. The problem: As soon as any user inserts a special character, like ‘, “, >, < or & and so on, the operation fails of course. First I thought of encoding the variables by the server with an ajax request but I did not want to use up so much traffic. So I came up with this tiny function that works similar to htmlentities but encodes every character, also normal ASCII characters. It does not really encode the characters to html entites but to xml entities which is fine for its use in HTML.
Here is the function:

<script type="text/javascript">
function htmlentities(input)
{
    var code="";
    for(i=0; i < input.length; i++)
    {
        code=code+"&#"+input.charCodeAt(i)+";";
    }
    return code;
}
</script>

If you want to test it, you can do it here:

Input


Raw Output

Output with encoded entities (you will not see any change compared to the input)



This is the code for the code playground above. As you can see it is very simple.

Input
<textarea id="input" rows="3" cols="60">&#115;&#112;&#101;&#99;&#105;&#97;&#108;&#32;&#99;&#104;&#97;&#114;&#97;&#99;&#116;&#101;&#114;&#115;&#58;&#32;&#60;&#62;&#8221;&#38;&#8217;&#32;&#109;&#111;&#114;&#101;&#32;&#115;&#112;&#101;&#99;&#105;&#97;&#108;&#32;&#99;&#104;&#97;&#114;&#97;&#99;&#116;&#101;&#114;&#115;&#58;&#32;&#9835;&#9834;&#32;&#9660;&#9650;&#9660;&#9650;&#32;&#110;&#111;&#114;&#109;&#97;&#108;&#32;&#99;&#104;&#97;&#114;&#97;&#99;&#116;&#101;&#114;&#115;&#58;&#32;&#97;&#98;&#99;&#49;&#50;&#51;</textarea>
<input onclick="javascript:document.getElementById('output').value=htmlentities(document.getElementById('input').value); document.getElementById('enc_output').innerHTML=htmlentities(document.getElementById('input').value);" type="button" value="Run htmlentities()" />
Raw Output
<textarea id="output" rows="3" cols="60"></textarea>
Output with encoded entities (you will not see any change compared to the input)
<textarea id="enc_output" rows="3" cols="60"></textarea>

« »