Converting sanitised html back to displayable html

后端 未结 5 972
北荒
北荒 2020-12-05 18:41

I\'m getting html data from a database which has been sanitised.

Basically what I\'m getting is something like this:

<div class=\"someclass\"&         


        
5条回答
  •  失恋的感觉
    2020-12-05 18:46

    The example from CMS, while good, does not take in account that for example "script" things will get parsed in the div and then not returned at all.

    So I wrote the following simple extension to the strings prototype

    if (!String.prototype.unescapeHTML) {
        String.prototype.unescapeHTML = function() {
            return this.replace(/&[#\w]+;/g, function (s) {
                var entityMap = {
                    "&": "&",
                    "<": "<",
                    ">": ">",
                    '"': '"',
                    ''': "'",
                    '/': "/"
                };
    
                return entityMap[s];
            });
        };
    }
    

    This will keep "scripts" in the text and not drop them

    Example

    I will make things bad <b>because evil</b>
    
    <script language="JavaScript">console.log('EVIL CODE');</script>
    

    will drop the "script" part with the CMS style way, but with the string unescapeHTML it will keep it

提交回复
热议问题