JS UrlDecode () and UrlEncode method support Chinese decoding

Source: Internet
Author: User
Tags chr urlencode
The code is as follows Copy Code


<script language= "VBScript" >
Function STR2ASC (STRSTR)
STR2ASC = Hex (ASC (STRSTR))
End Function
Function Asc2str (ASCASC)
ASC2STR = Chr (ASCASC)
End Function
</script>
<script language= "javascript" type= "Text/javascript" >
function UrlEncode (str) {
var ret= "";
var strspecial= "!" #$%& ' () *+,/:;<=>? []^`{|} ~%";
for (Var i=0;i<str.length;i++) {
var chr = Str.charat (i);
var c=str2asc (CHR);
if (parseint ("0x" +c) > 0x7f) {
ret+= "%" +c.slice (0,2) + "%" +c.slice (-2);
}else{
if (chr== "")
ret+= "+";
else if (Strspecial.indexof (CHR)!=-1)
ret+= "%" +c.tostring (16);
Else
RET+=CHR;
}
}
return ret;
}
</script>

Use this method to invoke:

The code is as follows Copy Code

<script language= "javascript" type= "Text/javascript" >
Alert (UrlEncode ("Sun Yupo Good Man"));
</script>


Decoding method

The code is as follows Copy Code

function UrlDecode (ZIPSTR) {
var uzipstr= "";
for (Var i=0;i<zipstr.length;i++) {
var chr = Zipstr.charat (i);
if (Chr = = "+") {
uzipstr+= "";
}else if (chr== "%") {
var asc = zipstr.substring (i+1,i+3);
if (parseint ("0x" +asc) >0x7f) {
Uzipstr+=decodeuri ("%" +asc.tostring () +zipstr.substring (i+3,i+9). toString ());
i+=8;
}else{
Uzipstr+=asciitostring (parseint ("0x" +asc));
i+=2;
}
}else{
uzipstr+= CHR;
}
}

return uzipstr;
}

function Stringtoascii (str) {
Return str.charcodeat (0). toString (16);
}
function asciitostring (asccode) {
Return String.fromCharCode (Asccode);
}

Usage

How to use

  code is as follows copy code

var str = '% E7%90%bc%e5%8f%b0%e5%8d%9a%e5%ae%a2 ';
var destr = UrlDecode (str);
Alert (DESTR);

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.