這三個javascript的函式,都是對字串作編碼,各自有一些些差異

紀錄一下用法與差異


  1. escape(string)
    用途:將字串中的字元做十六進位的編碼。
    回傳值:已編碼的字串結果。
    例:
    var res=escape(‘https://www.google.com.tw/webhp?ie=UTF-8#q=哈囉’);
    res => “https%3A//www.google.com.tw/webhp%3Fie%3DUTF-8%23q%3D%u54C8%u56C9″ps. 不對ascii 字母及數字做編碼,對 * @ – _ + . / 也不做編碼
    除此之外,escape 已被 ecma 標準拋棄,建議改用以下兩者
  2. encodeURI(string)
    用途:將字串中的字元做編碼,以符合URI格式。
    回傳值:轉換後符合URI格式的字串。
    例:
    var res=encodeURI(‘https://www.google.com.tw/webhp?ie=UTF-8#q=哈囉’);
    res => “https://www.google.com.tw/webhp?ie=UTF-8#q=%E5%93%88%E5%9B%89”
    ps. 不對ascii 字母及數字做編碼,對 , / ? : @ & = + $ # 也不做編碼
  3. encodeURIComponent(string)
    用途:和encodeURI() 效果差不多,但會對符號做編碼,通常用在url的參數(payload)部分。
    回傳值:轉換後符合URI格式的字串。
    例:
    var res=encodeURIComponent(‘https://www.google.com.tw/webhp?ie=UTF-8#q=哈囉’);
    res => “https%3A%2F%2Fwww.google.com.tw%2Fwebhp%3Fie%3DUTF-8%23q%3D%E5%93%88%E5%9B%89″ps. 可以發現若將整個url傳進去,編碼後已經不再是一個可以發出http request的 url (http://),因此通常會僅傳入參數部分。

4 Comments

  • I’ve been browsing on-line greater than 3 hours lately, but
    I by no means found any interesting article like yours. It
    is beautiful worth sufficient for me. In my view, if all webmasters and bloggers made good content
    as you did, the internet shall be a lot more helpful than ever before.

  • I’ll immediately grab your rss as I can’t in finding your email subscription hyperlink or e-newsletter
    service. Do you’ve any? Please let me recognize in order that I may subscribe.
    Thanks.

Leave a Reply