HtmlSpecialChars equivalent in Javascript?

后端 未结 16 1526
耶瑟儿~
耶瑟儿~ 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:15

    function htmlEscape(str){
        return str.replace(/[&<>'"]/g,x=>'&#'+x.charCodeAt(0)+';')
    }
    

    This solution uses the numerical code of the characters, for example < is replaced by <.

    Although its performance is slightly worse than the solution using a map, it has the advantages:

    • Not dependent on a library or DOM
    • Pretty easy to remember (you don't need to memorize the 5 HTML escape characters)
    • Little code
    • Reasonably fast (it's still faster than 5 chained replace)

提交回复
热议问题