Can I escape html special chars in javascript?

后端 未结 15 1444
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 02:26

I want to display a text to HTML by a javascript function. How can I escape html special chars in JS? Is there an API ?

15条回答
  •  灰色年华
    2020-11-22 03:05

    You can use jQuery's .text() function.

    For example:

    http://jsfiddle.net/9H6Ch/

    From the jQuery documentation regarding the .text() function:

    We need to be aware that this method escapes the string provided as necessary so that it will render correctly in HTML. To do so, it calls the DOM method .createTextNode(), does not interpret the string as HTML.

    Previous Versions of the jQuery Documentation worded it this way (emphasis added):

    We need to be aware that this method escapes the string provided as necessary so that it will render correctly in HTML. To do so, it calls the DOM method .createTextNode(), which replaces special characters with their HTML entity equivalents (such as &lt; for <).

提交回复
热议问题