Unescape HTML entities in Javascript?

前端 未结 30 3041
野趣味
野趣味 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 06:02

    There is an variant that 80% as productive as the answers at the very top.

    See the benchmark: https://jsperf.com/decode-html12345678/1

    performance test

    console.log(decodeEntities('test: >'));
    
    function decodeEntities(str) {
      // this prevents any overhead from creating the object each time
      const el = decodeEntities.element || document.createElement('textarea')
    
      // strip script/html tags
      el.innerHTML = str
        .replace(/]*>([\S\s]*?)<\/script>/gmi, '')
        .replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '');
    
      return el.value;
    }

    If you need to leave tags, then remove the two .replace(...) calls (you can leave the first one if you do not need scripts).

提交回复
热议问题