Implementation of htmlencode () and htmldecode () function instance analysis using alternative javascript methods

Source: Internet
Author: User
An example of how to implement the htmlencode () and htmldecode () functions in javascript is described in this document. We will share this with you for your reference. The details are as follows:

The most common practice is to replace special characters such as <> & with regular expressions. It is easier to replace special characters such as <> & with htmlencode, however, it may not be easy to use when htmldecode is sent, because there are many situations that need to be reversed. There are also dozens of character entities such as <>, in addition, it is difficult to list all escape characters in the Unicode-encoded decimal or hexadecimal notation such as AB Chinese or Chinese. 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 p = document.createElement('p');  p.appendChild(document.createTextNode(s));  return p.innerHTML;}function htmldecode(s){  var p = document.createElement('p');  p.innerHTML = s;  return p.innerText || p.textContent;}

Very concise!

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

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

Test:

// Test document. onclick = function (){//

&

Alert (htmlencode ('

&

'));//

& ABC Chinese

Alert (htmldecode ('

& ABC Chinese

'));}

Good results.

Htmldecode requires an input parameter. If the input parameter is not the result of a valid encode, the expected result may not be obtained.

I searched in google and found an article in cnblogs that had the same idea as me. Someone else thought like this ||=, but his htmldecode code has an error.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.