HtmlSpecialChars equivalent in Javascript?

后端 未结 16 1560
耶瑟儿~
耶瑟儿~ 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条回答
  •  旧时难觅i
    2020-11-22 06:25

    Here's a function to escape HTML:

    function escapeHtml(str)
    {
        var map =
        {
            '&': '&',
            '<': '<',
            '>': '>',
            '"': '"',
            "'": '''
        };
        return str.replace(/[&<>"']/g, function(m) {return map[m];});
    }
    

    And to decode:

    function decodeHtml(str)
    {
        var map =
        {
            '&': '&',
            '<': '<',
            '>': '>',
            '"': '"',
            ''': "'"
        };
        return str.replace(/&|<|>|"|'/g, function(m) {return map[m];});
    }
    

提交回复
热议问题