Unescape HTML entities in Javascript?

前端 未结 30 3543
野趣味
野趣味 2020-11-21 05:40

I have some Javascript code that communicates with an XML-RPC backend. The XML-RPC returns strings of the form:


30条回答
  •  孤城傲影
    2020-11-21 05:48

    This is the most comprehensive solution I've tried so far:

    const STANDARD_HTML_ENTITIES = {
        nbsp: String.fromCharCode(160),
        amp: "&",
        quot: '"',
        lt: "<",
        gt: ">"
    };
    
    const replaceHtmlEntities = plainTextString => {
        return plainTextString
            .replace(/&#(\d+);/g, (match, dec) => String.fromCharCode(dec))
            .replace(
                /&(nbsp|amp|quot|lt|gt);/g,
                (a, b) => STANDARD_HTML_ENTITIES[b]
            );
    };
    

提交回复
热议问题