Home Web Front-end JS Tutorial How to convert html characters to entities in javascript

How to convert html characters to entities in javascript

Jul 21, 2021 am 10:37 AM
js

<p>方法:1、使用innerHTML设置或获取标签所包含的HTML+文本信息(从标签起始位置到终止位置全部内容,包括HTML标签);2、使用innerText设置或获取标签所包含的文本信息(从标签起始位置到终止位置的内容,去除HTML标签)。

<p>How to convert html characters to entities in javascript

<p>本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。

<p>针对这个问题,可以分为两种情况:一种是只包含&、<、>、'的html实体,另一种是广义的实体,不只局限于上面的情况。对于后者,在我看来,除了列举出所有的实体符号,写switch case语句,还真的没有什么好办法。(如果您有什么好办法,请不吝赐教。)。针对前者的话,其实原生js就支持。例如会自动对文本中存在的HTML语法字符(小于号、大于号、引号及和号)进行编码的节点的innerText属性(FireFox中是textContent属性。

<p>实际上二者并不完全一样,innerText会忽略行内样式和脚本,而textContent则会原样返回行内样式和文本。)。其原理是设置innerText会生成当前节点的一个子文本节点,而为了确保只生成一个子文本节点,就需要对文本进行HTML编码。innerHTML虽然也可以做到,但它转变的只是标签的文本。下面的例子展示了它们的不同。

var div=document.createElement(&#39;div&#39;);
div.innerText=&#39;<p>hello & world</p>&#39;;
div.innerText //<p>hello & world</p>"
div.innerHTML //"&lt;p&gt;hello &amp; world&lt;/p&gt;"

div.innerHTML=&#39;<p>hello & < world</p>&#39;
div.innerHTML //"<p>hello &amp; &lt;  world</p>"
div.innerText //"hello & < world"
Copy after login
<p>从上面例子中可以看到二者的区别:innerText会将所有的文本转义(当然也不是全部文本,比如空格就不会),innerHTML则是对标签內的文本进行转义,标签如<p>就不会转义,但孤立的小于大于号还是会进行转换的。(上面代码中innerHTML之所以设置的内容和解析后的内容不一样,是因为返回的是浏览器根据原始字符串解析为DOM树后经过序列化之后的结果。)根据上面程序的结果,我们可以得到简单的转换函数:

//仅限于包含`&、<、>、&#39;`的文本转换
function stringToEntity(str){
  var div=document.createElement(&#39;div&#39;);
  div.innerText=str;
  div.textContent=str;
  var res=div.innerHTML;
  console.log(str,&#39;->&#39;,res);
  return res;
}
Copy after login
<p>其实除了innerText,还可以通过创建文本节点的方式来完成转义,即使用document.createTextNode()。这种方法大部分的应用场景是对用户输入进行转义。例如业务需要,我们需要把用户的输入写到网页上,不做转义直接将用户输入写到网页上往往是行不通的,因为容易出现XSS漏洞。不过我们可以通过document.createTextNode()方法将用户输入作为文本节点,然后再插入到文档中。该方法会对出现的特殊标记进行转义。例如如下代码:

var str="<img src=&#39;a valid url&#39; οnlοad=&#39;alert(1)&#39;></img>";
var text=document.createTextNode(str);
$("container").appendChild(text);
Copy after login
<p>上述代码中如果不加转义直接使用$("container").innerHTML=str;就会使得图片加载完运行onload里面的代码,如果代码是恶意的,就会为我们网站的用户造成损害。而将小于号、大于号转义后就不会出现这个问题了。

<p>【推荐学习:javascript高级教程】  

The above is the detailed content of How to convert html characters to entities in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to use JS and Baidu Maps to implement map pan function How to use JS and Baidu Maps to implement map pan function Nov 21, 2023 am 10:00 AM

How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to create a stock candlestick chart using PHP and JS How to create a stock candlestick chart using PHP and JS Dec 17, 2023 am 08:08 AM

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

How to use JS and Baidu Map to implement map click event processing function How to use JS and Baidu Map to implement map click event processing function Nov 21, 2023 am 11:11 AM

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

How to use JS and Baidu Maps to implement map heat map function How to use JS and Baidu Maps to implement map heat map function Nov 21, 2023 am 09:33 AM

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

See all articles