str.escapeHTML()

๐Ÿ”ฐ JS โŸฉ Types โŸฉ String โŸฉ methods

๐Ÿ’พ ็จ‹ๅผ๏ผšcodepen โŸฉ escapeHTML() โญ๏ธ

// โญ๏ธ escapeHTML()
export function escapeHTML(str){
    return new Option(str).innerHTML;
}

// โญ๏ธ str.escapeHTML()
String.prototype.escapeHTML = function(){
    return escapeHTML(this);
}

// โญ๏ธ escape HTML special characters (deprecatedโ—๏ธ)
String.prototype.escapeHTML = function () {
    return this 
        .replace(/&/g, '&' )    // ampersand (must be firstโ—๏ธ)
        .replace(/>/g, '>'  )    // greater than
        .replace(/</g, '&lt;'  )    // less than
        .replace(/"/g, '&quot;')    // double-quote
        .replace(/'/g, '&#39;' )    // single-quote
        .replace(/`/g, '&#96;' );   // backtick
}

Last updated

Was this helpful?