Html string encoding code in Javascript

Source: Internet
Author: User

Sometimes we will <> this type of characters in html, and we need to convert it into html character encoding for ease of use. Let's look at an example below.

An html string is a string with special html characters such as '<div id = "a"> aklsdjfklsjdfl </div>, we usually need to process it before outputting it so as not to output it into a real html element, that is, to convert <into html symbol code like <.

If the string is long and contains many special characters, how can we simply and efficiently transcode all of them? Loop? Regular Expression? No! See:

The Code is as follows: Copy code

Function bian (a) {return new Option (a). innerHTML}

This is all! Usage:

The Code is as follows: Copy code

Function bian (a) {return new Option (a). innerHTML}
Var a = '<div id = "a"> aklsdjfklsjdfl </div> ';
Alert (bian ());

By replacing special characters

1) HTML encoding:

The Code is as follows: Copy code

Function HTMLEnCode (str)
{
Var s = "";
If (str. length = 0) return "";
S = str. replace (/&/g, "& gt ;");
S = s. replace (/</g, "& lt ;");
S = s. replace (/>/g, "& gt ;");
S = s. replace (// g, "& nbsp ;");
S = s. replace (/'/g ,"'");
S = s. replace (/"/g," & quot ;");
S = s. replace (/n/g, "<br> ");
Return s;
}

2) HTML Decoding:

The Code is as follows: Copy code

Function HTMLDeCode (str)
{
Var s = "";
If (str. length = 0) return "";
S = str. replace (/& gt;/g ,"&");
S = s. replace (/& lt;/g, "<");
S = s. replace (/& gt;/g, "> ");
S = s. replace (/& nbsp;/g ,"");
S = s. replace (/'/g ,"'");
S = s. replace (/& quot;/g ,""");
S = s. replace (/<br>/g, "n ");
Return s;
}

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.