用JavaScript实现UrlEncode和UrlDecode

| No Comments | No TrackBacks

1、

<script language="vbscript">
/*利用VBScript构建asc吗和字符串的互转函数*/
Function str2asc(strstr)
 str2asc = hex(asc(strstr))
End Function
Function asc2str(ascasc)
 asc2str = chr(ascasc)
End Function
</script>


<script language="javascript">
/*这里开始时UrlEncode和UrlDecode函数*/
function UrlEncode(str){
  var ret="";
  var strSpecial="!"#$%&'()*+,/:;<=>?[]^`{|}~%";
  for(var i=0;i<str.length;i++){
   var chr = str.charAt(i);
    var c=str2asc(chr);
    tt += chr+":"+c+"n";
    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;
}
function UrlDecode(str){
  var ret="";
  for(var i=0;i<str.length;i++){
   var chr = str.charAt(i);
    if(chr == "+"){
      ret+=" ";
    }else if(chr=="%"){
     var asc = str.substring(i+1,i+3);
     if(parseInt("0x"+asc)>0x7f){
      ret+=asc2str(parseInt("0x"+asc+str.substring(i+4,i+6)));
      i+=5;
     }else{
      ret+=asc2str(parseInt("0x"+asc));
      i+=2;
     }
    }else{
      ret+= chr;
    }
  }
  return ret;
}
</script>

2、

function urlencode(str)
tmp=""
strSpecial="_-.1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i=1 to len(str)
  crt=mid(str,i,1)
  if instr(1,strSpecial,crt,1) then  
   tmp=tmp&crt  
  else
   hexc=hex(asc(crt))
   tmp=tmp&"%"& mid(hexc,1,2)
   if len(hexc)>2 then
    tmp=tmp&"%"& mid(hexc,3,2)
   end if
  end if  
next
urlencode=tmp
end function

3、

<script language="vbscript">

function urlencode(vstrin)
    dim i,strreturn,strSpecial
    strSpecial = " <>""#%{}|^~[]`'&?+"
    strreturn = ""
    for i = 1 to len(vstrin)
        thischr = mid(vstrin,i,1)
        if abs(asc(thischr)) < &hff then
            if instr(strSpecial,thischr)>0 then
                strreturn = strreturn & "%" & hex(asc(thischr))
            else
                strreturn = strreturn & thischr
            end if
        else
            innercode = asc(thischr)
            if innercode < 0 then
                innercode = innercode + &h10000
            end if
            hight8 = innercode '(innercode  and &hff00)' mod &hff
            low8 = innercode and &hff
            strreturn = strreturn & "%" & hex(hight8) &  "%" & hex(low8)
        end if
    next
    urlencoding = strreturn
end function
document.write(urlencode("中文 <>""#%{}|^~[]`'&?+Abc")+"<br>")
</script>

No TrackBacks

TrackBack URL: http://www.wujianrong.com/mt-tb.cgi/1414

Leave a comment

About this Entry

This page contains a single entry by kevinwu published on November 25, 2006 11:52 AM.

通过时间校验学习JavaScript正则表达式 was the previous entry in this blog.

JBuilder2007 打通任督二脉的崭新Java开发工具 is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.