[Javascript] HTML Escaping htmlspecialchars

Tadashi Shigeoka ·  Sat, August 18, 2012

Memo of code implementing the PHP function htmlspecialchars in Javascript to escape characters that have special meaning in HTML.

function htmlspecialchars(ch) { 
    ch = ch.replace(/&/g,"&") ;
    ch = ch.replace(/"/g,""") ;
    ch = ch.replace(/'/g,"'") ;
    ch = ch.replace(//g,">") ;
    return ch ;
}

【Reference】

Javascript で HTMLエスケープを行うPHP関数、htmlspecialchars を実装:phpspot開発日誌

That’s all from the Gemba.