HtmlSpecialChars equivalent in Javascript?

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

    I am elaborating a bit on o.k.w.'s answer.

    You can use the browser's DOM functions for that.

    var utils = {
        dummy: document.createElement('div'),
        escapeHTML: function(s) {
            this.dummy.textContent = s
            return this.dummy.innerHTML
        }
    }
    
    utils.escapeHTML('&')
    

    This returns <escapeThis>&

    It uses the standard function createElement to create an invisible element, then uses the function textContent to set any string as its content and then innerHTML to get the content in its HTML representation.

提交回复
热议问题