Unescape HTML entities in Javascript?

前端 未结 30 2916
野趣味
野趣味 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:03

    Do you need to decode all encoded HTML entities or just & itself?

    If you only need to handle & then you can do this:

    var decoded = encoded.replace(/&/g, '&');
    

    If you need to decode all HTML entities then you can do it without jQuery:

    var elem = document.createElement('textarea');
    elem.innerHTML = encoded;
    var decoded = elem.value;
    

    Please take note of Mark's comments below which highlight security holes in an earlier version of this answer and recommend using textarea rather than div to mitigate against potential XSS vulnerabilities. These vulnerabilities exist whether you use jQuery or plain JavaScript.

提交回复
热议问题