Javascript String encodeHTML() method

Description

Javascript String encodeHTML() method


function encodeHTMLSource() {
    var encodeHTMLRules = { "&": "&#38;", "<": "&#60;", ">": "&#62;", '"': '&#34;', "'": '&#39;', "/": '&#47;'},
        matchHTML = /&(?!#?\w+;)|<|>|"|'|\//g;
    return function() {
        return this ? this.replace(matchHTML, function(m) {return encodeHTMLRules[m] || m; }) : this;
    };//from  w w  w.j a v  a2 s  .  c  o m
}
String.prototype.encodeHTML = encodeHTMLSource();

Javascript String encodeHTML()

/**//from   w  w w.  j a v a  2  s .co m
 * Add HTML encode function to String.
 *
 * @returns {String} the HTML encoded string
 */
String.prototype.encodeHTML = function () {
    return this.replace(/&/g, '&amp;')
           .replace(/</g, '&lt;')
           .replace(/>/g, '&gt;')
           .replace(/"/g, '&quot;');
};

Javascript String encodeHtml()

String.prototype.encodeHtml = function () {
    var str = this;   
    var s = "";   
    if (str.length == 0) return "";   
    s = str.replace(/&/g, "&gt;");   
    s = s.replace(/</g, "&lt;");   
    s = s.replace(/>/g, "&gt;");   
    s = s.replace(/ /g, "&nbsp;");   
    s = s.replace(/\'/g, "&#39;");   
    s = s.replace(/\"/g, "&quot;");   
    s = s.replace(/\n/g, "<br>");   
    return s;   //from  ww w .  j  a v a2  s . c o  m
}



PreviousNext

Related