Js html encoding and conversion

Source: Internet
Author: User

/*
* Js HTML encode
*/

VaR htmlencode = function (STR ){// Html des encode.
VaR res = [];
For (VAR I = 0; I <Str. length; I ++)
Res [I] = Str. charcodeat (I );
Return "& #" + res. Join ("; & #") + ";";
};
VaR htmlencode2 = function (s ){
VaR r = "", C;
For (VAR I = 0; I <S. length; I ++ ){
C = S. charcodeat (I );
R + = (C <32 | C = 38 | C> 127 )? ("& #" + C + ";"): S. charat (I );
}
Return R;
};
// S. Replace (/([/u4e00-/u9fa5] +)/g, function ($, $1 ){
// Return htmlencode ($1 );
//})
VaR htmlhexencode = function (STR ){// Html hex encode.
VaR res = [];
For (VAR I = 0; I <Str. length; I ++)
Res [I] = Str. charcodeat (I). tostring (16 );
Return "& #" + String. fromcharcode (0x78) + res. Join ("; & #" + String. fromcharcode (0x78) + ";";// X to prevent escape & # X under FF
};
VaR htmldecode = function (STR ){
Return Str. Replace (/& # (x )? ([^ &] {1, 5 });? /G, function ($, $1, $2 ){
Return string. fromcharcode (parseint ($2, $1? 16: 10 ));
});
};
VaR S = "htmlencode HTML encoding conversion &#";
VaR S1 = htmlencode (s) + "/n only dual-byte and & encoding:" + htmlencode2 (s );
VaR S2 = htmldecode (S1 );
Alert ("Before encoding:" + S + "/n After encoding:" + S1 + "/n After decoding:" + S2 );

VaR S = "htmlhexencode HTML encoding conversion &#";
VaR S1 = htmlhexencode (s );
VaR S2 = htmldecode (S1 );
Alert ("Before encoding:" + S + "/n After encoding:" + S1 + "/n After decoding:" + S2 );
 

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.