Unescape HTML entities in Javascript?

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

    The question doesn't specify the origin of x but it makes sense to defend, if we can, against malicious (or just unexpected, from our own application) input. For example, suppose x has a value of & . A safe and simple way to handle this in jQuery is:

    var x    = "& ";
    var safe = $('
    ').html(x).text(); // => "& alert('hello');"

    Found via https://gist.github.com/jmblog/3222899. I can't see many reasons to avoid using this solution given it is at least as short, if not shorter than some alternatives and provides defence against XSS.

    (I originally posted this as a comment, but am adding it as an answer since a subsequent comment in the same thread requested that I do so).

提交回复
热议问题