用JavaScript实现PHP的urlencode与urldecode函数
很多朋友说JavaScript的decodeURI函数也可以实现,但有bug所有呢,下面看下下面的函数,经过测试使用暂时没什么问题,我在之前的文章说过,这个和php的urldecode函数根本不是一回事。下面是我根据高人的代码改写的JavaScript版的urldecode函数,参考的链接在开头提到的文章中有,就不一一列举了。和之前的urlencode函数一样,只实现了utf-8版的。
1、urlencode
使用方法:urlencode(str);
functionurlencode(clearString)
{
varoutput='';
varx=0;
clearString=utf16to8(clearString.toString());
varregex=/(^[a-zA-Z0-9-_.]*)/;
while(x<clearString.length)
{
varmatch=regex.exec(clearString.substr(x));
if(match!=null&&match.length>1&&match[1]!='')
{
output+=match[1];
x+=match[1].length;
}
else
{
if(clearString[x]=='')
output+='+';
else
{
varcharCode=clearString.charCodeAt(x);
varhexVal=charCode.toString(16);
output+='%'+(hexVal.length<2?'0':'')+hexVal.toUpperCase();
}
x++;
}
}
functionutf16to8(str)
{
varout,i,len,c;
out="";
len=str.length;
for(i=0;i<len;i++)
{
c=str.charCodeAt(i);
if((c>=0x0001)&&(c<=0x007F))
{
out+=str.charAt(i);
}
elseif(c>0x07FF)
{
out+=String.fromCharCode(0xE0|((c>>12)&0x0F));
out+=String.fromCharCode(0x80|((c>>6)&0x3F));
out+=String.fromCharCode(0x80|((c>>0)&0x3F));
}
else
{
out+=String.fromCharCode(0xC0|((c>>6)&0x1F));
out+=String.fromCharCode(0x80|((c>>0)&0x3F));
}
}
returnout;
}
returnoutput;
}
2、urldecode
使用方法:urldecode(url);
functionurldecode(encodedString)
{
varoutput=encodedString;
varbinVal,thisString;
varmyregexp=/(%[^%]{2})/;
functionutf8to16(str)
{
varout,i,len,c;
varchar2,char3;
out="";
len=str.length;
i=0;
while(i<len)
{
c=str.charCodeAt(i++);
switch(c>>4)
{
case0:case1:case2:case3:case4:case5:case6:case7:
out+=str.charAt(i-1);
break;
case12:case13:
char2=str.charCodeAt(i++);
out+=String.fromCharCode(((c&0x1F)<<6)|(char2&0x3F));
break;
case14:
char2=str.charCodeAt(i++);
char3=str.charCodeAt(i++);
out+=String.fromCharCode(((c&0x0F)<<12)|
((char2&0x3F)<<6)|
((char3&0x3F)<<0));
break;
}
}
returnout;
}
while((match=myregexp.exec(output))!=null
&&match.length>1
&&match[1]!='')
{
binVal=parseInt(match[1].substr(1),16);
thisString=String.fromCharCode(binVal);
output=output.replace(match[1],thisString);
}
//output=utf8to16(output);
output=output.replace(/\\+/g,"");
output=utf8to16(output);
returnoutput;
}
当服务器端通过php的urlencode转码的就可以使用js的urldecode进行解析即可。