Home > Web Front-end > JS Tutorial > body text

Example analysis of javascript alternative methods to implement htmlencode() and htmldecode() functions

高洛峰
Release: 2016-12-06 15:11:53
Original
1237 people have browsed it

The example in this article describes the alternative method of JavaScript to implement the htmlencode() and htmldecode() functions. Share it with everyone for your reference. The details are as follows:

The most common method is to use regular expression replacement to replace special characters such as < > &. It is easier to replace like this when htmlencoding, but send it here It may not be easy to use when decoding html, because there are many situations that need to be reversed. In addition to the common <>&, there are also dozens of character entities such as ©"®, as well as AB Chinese or Chinese and so on. It is difficult to enumerate all the escapes of Unicode encoded decimal or hexadecimal representation of characters. Replacing them one by one is not only lengthy and inefficient, but also easy to miss some characters.

The code is as follows:

function htmlencode(s){
  var div = document.createElement(&#39;div&#39;);
  div.appendChild(document.createTextNode(s));
  return div.innerHTML;
}
function htmldecode(s){
  var div = document.createElement(&#39;div&#39;);
  div.innerHTML = s;
  return div.innerText || div.textContent;
}
Copy after login

Quite. Simple!

The encoding principle is to create a TextNode node, attach it to the container, and then get the innerHTML of the container.

The decoding principle is to assign the string to the innerHTML of the container, and then get the innerText or textContent.

Test it:

//测试
document.onclick = function (){
  //<p> & </p>
  alert(htmlencode(&#39;<p> & </p>&#39;));
  //<p> & © ABC 中文 中文 </p>
  alert(htmldecode(&#39;<p> & © ABC 中文 中文 </p>&#39;));
}
Copy after login

The effect is good.

htmldecode has requirements for input parameters. If the input parameters are not legal encoded results, the expected results may not be obtained.

I searched on google and found an article with the same idea as mine on cnblogs. , it turns out that someone else has thought this way =||=, but his htmldecode code is wrong


.
Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!