HtmlSpecialChars equivalent in Javascript?

后端 未结 16 1875
耶瑟儿~
耶瑟儿~ 2020-11-22 06:00

Apparently, this is harder to find than I thought it would be. And it even is so simple...

Is there a function equivalent to PHP\'s htmlspecialchars built into Javas

16条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 06:36

    Hope this wins the race due to its performance and most important not a chained logic using .replace('&','&').replace('<','<')...

    var mapObj = {
       '&':"&",
       '<':"<",
       '>':">",
       '"':""",
       '\'':"'"
    };
    var re = new RegExp(Object.keys(mapObj).join("|"),"gi");
    
    function escapeHtml(str) 
    {   
        return str.replace(re, function(matched)
        {
            return mapObj[matched.toLowerCase()];
        });
    }
    
    console.log('');
    console.log(escapeHtml(''));
    

提交回复
热议问题