技術(shù)頻道導(dǎo)航
HTML/CSS
.NET技術(shù)
IIS技術(shù)
PHP技術(shù)
Js/JQuery
Photoshop
Fireworks
服務(wù)器技術(shù)
操作系統(tǒng)
網(wǎng)站運營

贊助商

分類目錄

贊助商

最新文章

搜索

JavaScript Base64 和 URL 編碼解碼實例

作者:admin    時間:2021-8-5 10:28:5    瀏覽:

在本文中,我們將探討 JavaScript 編碼解碼功能。

在 JavaScript 中,下面這些是對Base64字符串和URL進行編碼和解碼的函數(shù)。

  • btoa():此函數(shù)使用A-Za-z0-9+/=字符以 Base64 對字符串進行編碼。
  • atob():對 btoa() 編碼的字符串解碼.
  • encodeURI():此函數(shù)用于對URI進行編碼。
  • decodeURI():對 encodeURI() 編碼的字符串解碼。

我們也可以使用以下函數(shù)對 URI 進行編碼和解碼。

  • encodeURIComponent(uriToEncode)
  • decodeURIComponent(encodedURI)

1. JavaScript btoa()

句法

var encodedString = window.btoa(stringToEncode);

參數(shù)

stringToEncode – 要編碼的二進制字符串。

返回

stringToEncode 的Base64字符串。

例外

InvalidCharacterError– 字符串包含無效字符。

例子

var originalString = "Love the way you lie";

var encodedString = window.btoa(originalString);

console.log(encodedString);

輸出

TG92ZSB0aGUgd2F5IHlvdSBsaWU=

trying >>

2. JavaScript atob()

句法

var decodedString = window.atob(encodedString);

參數(shù)

encodingString – 由 btoa() 生成的編碼字符串。

異常

DOMException - 如果encodingString不是有效的 Base64。

例子

var encodedString = "TG92ZSB0aGUgd2F5IHlvdSBsaWU=";

var decodedString = window.atob(encodedString);

console.log(decodedString);

輸出

Love the way you lie

trying >>

3. JavaScript 編碼URI()

句法

var encodedURL = window.encodeURI(uriToEncode);

參數(shù)

uriToEncode – 完整的 URI。

返回

表示提供的字符串的新字符串,編碼為 URI。

例子

var originalURL = "http://www.howtostagehomes.com/?s=卡卡網(wǎng)";

var encodedURL = window.encodeURI(originalURL);

console.log(encodedURL);

輸出

http://www.howtostagehomes.com/?s=%E5%8D%A1%E5%8D%A1%E7%BD%91

trying >>

4. JavaScript decodeURI()

句法

var decodedURL = window.decodeURI(encodedURL);

參數(shù)

endcodedURL – 由endcodedURI()函數(shù)生成的編碼 URI 字符串。

返回

表示給定編碼統(tǒng)一資源標識符 ( URI )的未編碼版本的新字符串。

異常

URIError – 當(dāng) encodingURI 包含無效字符時的異常。

例子

var encodedURL = "http://www.howtostagehomes.com/?s=%E5%8D%A1%E5%8D%A1%E7%BD%91";

var decodedURL = window.decodeURI(encodedURL);

console.log(decodedURL);

輸出

http://www.howtostagehomes.com/?s=卡卡網(wǎng)

trying >>

或者,我們也可以使用如下函數(shù)分別對 URI 進行編碼和解碼。

  • encodeURIComponent(uriToEncode)
  • decodeURIComponent(encodedURI)

總結(jié)

本文介紹了如何使用函數(shù)對字符串進行 Base64 加密和解密,以及對 URL 進行編碼和解碼。

相關(guān)文章
    x
    • 站長推薦
    /* 左側(cè)顯示文章內(nèi)容目錄 */