JS對字串編碼的幾種方式使用

來源:互聯網
上載者:User

JS對字串編碼的幾種方式使用

   在用戶端中,要對字串編碼,可以採用:escape();encodeurl();encodeURIComponent();下面我們就來具體講解下這幾個方法。

  函數 描述

  encodeURI() 把字串編碼為 URI

  encodeURIComponent() 把字串編碼為 URI 組件

  escape() 對字串進行編碼

  上面是查詢來自w3school的資料。那麼三者之間有什麼區別呢,請容我測試測試。

   代碼如下:

  var str = "http://localhost:8080/Product/index?id=123&attr=456&area=中國";

  console.log(encodeURI(str));

  console.log(encodeURIComponent(str));

  console.log(escape(str));

  列印結果如下:

   代碼如下:

  http://localhost:8080/Product/index?id=123&attr=456&area=%E4%B8%AD%E5%9B%BD

  http%3A%2F%2Flocalhost%3A8080%2FProduct%2Findex%3Fid%3D123%26attr%3D456%26area%3D%E4%B8

%AD%E5%9B%BD

  http%3A//localhost%3A8080/Product/index%3Fid%3D123%26attr%3D456%26area%3D%u4E2D%u56FD

  可以看出,

  encodeURI不會對:/?&等uri中起分割作用的字元進行編碼;

  encodeURIComponent則會。

  觀察escape則發現,:?&都被轉碼了,而/沒有,w3school解釋是,escape函數會對ascii碼中字母、數字及符號( * @ - _ + . / )之外的所有字元進行編碼。

  另外,我們可以看出escape對漢字“中國”編碼後結果與前兩者不同。W3SCHOOL也建議不使用該方法,用前兩者代替。

  以上所述就是本文的全部內容了,希望對大家學習javascript能夠有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.