Javascript Function: htmlentities()

Convert html tags and code to readable HTML entities. Mimics the PHP functions htmlspecialchars() and htmlentities().
Prevents from HTML script injection.


The code (Updated July 14th):

function html_entity_decode(s) {
var t=document.createElement(’textarea’);
t.innerHTML = s;
var v = t.value;
t.parentNode.removeChild(t);
return v;
}

The old code, which still works:

function htmlentities(str) {
    var i,output='',len,char='';
    len = str.length;
    for(i=0;i47 && char<58)||(char>62 && char<127) ){
            output += str[i];
        }else{
            output += "&#" + str[i].charCodeAt(0) + ";";
        }
    }
    return output;
}

May also be good for encrypting email address’s. Will need slight modification.
Hope this function became as handy as it did for me.

Anyone need htmlunentities() or html_decode_entities(), hehe?

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

I think the best way to practice it is to get a nice book and use examples from that

Leave a comment

(required)

(required)