JavaScript中URL的解碼和編碼


這些URI方法encodeURI、encodeURIComponent()、decodeURI()、decodeURIComponent()代替了BOM的escape()和unescape()方法。

URI方法更可取,因為它們對所有Unicode符號編碼,而BOM方法只能對ASCII符號正確編碼。盡量避免使用escape()和unescape()方法。

                                                    ---摘自 javascript advanced book.

 

 

js對文字進行編碼涉及3個函數:escape、encodeURI、encodeURIComponent,相應3個解碼函數:unescape、decodeURI、decodeURIComponent

 

1、   傳遞參數時需要使用encodeURIComponent,這樣組合的url才不會被#等特殊字符截斷。                            

例如:<script language="javascript">document.write('<a href="http://passport.baidu.com/?logout&aid=7&u='+encodeURIComponent ("http://cang.baidu.com/bruce42")+'">退出</a>');</script>

 

2、   進行url跳轉時可以整體使用encodeURI

例如:Location.href=encodeURI(http://cang.baidu.com/do/s?word=百度&ct=21);

 

3、   js使用數據時可以使用escape

  例如:收藏中history紀錄。

 

4、   escape對0-255以外的unicode值進行編碼時輸出%u****格式,其它情況下escape,encodeURI,encodeURIComponent編碼結果相同。

最多使用的應為encodeURIComponent,它是將中文、韓文等特殊字符轉換成utf-8格式的url編碼,所以如果給后台傳遞參數需要使用encodeURIComponent時需要后台解碼對utf-8支持(form中的編碼方式和當前頁面編碼方式相同)

 

escape不編碼字符有69個:*,+,-,.,/,@,_,0-9,a-z,A-Z

encodeURI不編碼字符有82個:!,#,$,&,',(,),*,+,,,-,.,/,:,;,=,?,@,_,~,0-9,a-z,A-Z

encodeURIComponent不編碼字符有71個:!, ',(,),*,-,.,_,~,0-9,a-z,A-Z

 

========================================================

 

unescape 方法

從用 escape 方法編碼的 String 對象中返回已解碼的字符串。

function unescape(charString : String) : String


    參數

charString

必選。要解碼的 String 對象或文本。

備注

unescape 方法返回一個包含 charstring 內容的字符串值。所有以 %xx 十六進制形式編碼的字符都用 ASCII 字符集當中等效的字符代替。以 %uxxxx 格式(Unicode 字符)編碼的字符用十六進制編碼 xxxx 的 Unicode 字符代替。注意 unescape 方法不應用於解碼“統一資源標識符”(URI)。請改用 decodeURI 和 decodeURIComponent 方法。

 

decodeURI 方法

返回一個已編碼的統一資源標識符 (URI) 的非編碼形式。

function decodeURI(URIstring : String) : String

參數

URIstring

必選。表示編碼 URI 的字符串。

備注

使用 decodeURI 方法代替已經過時的 unescape 方法。

decodeURI 方法返回一個字符串值。

如果 URIString 無效,將發生 URIError。

 

decodeURIComponent 方法

返回統一資源標識符 (URI) 的一個已編碼組件的非編碼形式。

function decodeURIComponent(encodedURIString : String) : String

必選的 encodedURIString 參數是一個表示已編碼的 URI 組件的值。

備注:

URIComponent 是一個完整的 URI 的一部分

 

 

 

// 獲取查詢字符串參數
function getQueryStringArgs(){
    var qS = window.location.search.length>0?location.search.substring(1):"",
    args = {},
    items = qS.split("&"),
    len = items.length,
    name = null,
    value = null,
    item = null;
    if(qS.length == 0) {
        return args;
    };
    for(var i=0;i < len;i++){
        item = items[i].split("=");
        name = decodeURIComponent(item[0]);
        value = decodeURIComponent(item[1]);
        args[name] = value;
    }
    return args;
}



//查詢字符串參數
function getURIArgs(args)
{
    var s="";
    window.location.search.length && getQueryStringArgs()[args] ? s = getQueryStringArgs()[args] : s = "";
    return s;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM