首頁 > web前端 > js教程 > 主體

如何在 JavaScript 中對 URL 進行編碼和解碼?

WBOY
發布: 2023-09-09 14:29:21
轉載
988 人瀏覽過

任何網站的 URL 都需要對 URI 和 URI 元件進行編碼和解碼,以到達或重定向使用者。這是 Web 開發中常見的任務,通常是在使用查詢參數向 API 發出 GET 請求時完成的。查詢參數也必須編碼在 URL 字串中,伺服器將對其進行解碼。許多瀏覽器會自動對 URL 和回應字串進行編碼和解碼。

例如,空格「 」被編碼為 或 。

對URL 進行編碼

可以使用JavaScript 中的下列方法來完成特殊字元的轉換-
  • encodeURI() 函數 - encodeURI() 函數用於對完整的URI 進行編碼,將URI 中的特殊字元轉換為瀏覽器可理解的語言。一些未編碼的字元是:(, / ? : @ & = $ #)。

  • encodeURIComponent() 函數 - 這函數對整個 URL 而不僅僅是 URI 進行編碼。該組件還對網域名稱進行編碼。

語法

encodeURI(complete_uri_string )
encodeURIComponent(complete_url_string )
登入後複製

參數

  • #complete_uri_string string - 它保存要編碼的URL。

  • complete_url_string string - 它保存要編碼的完整 URL 字串。

上述函數傳回編碼後的 URL。

範例 1

在下面的範例中,我們使用encodeURI() 和encodeURIComponent() 方法對URL 進行編碼。

# index.html

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Encoding URI</title>
</head>
<body>
   <h1 style="color: green;">
      Welcome To Tutorials Point
   </h1>
   <script>
      const url="https://www.tutorialspoint.com/search?q=java articles";
      document.write(&#39;<h4>URL: </h4>&#39; + url)
      const encodedURI=encodeURI(url);
      document.write(&#39;<h4>Encoded URL: </h4>&#39; + encodedURI)
      const encodedURLComponent=encodeURIComponent(url);
      document.write(&#39;<h4>Encoded URL Component: </h4>&#39; + encodedURLComponent)
   </script>
</body>
</html>
登入後複製

輸出

如何在 JavaScript 中对 URL 进行编码和解码?

#解碼URL

##URL 的解碼可以使用以下方法完成-

  • decodeURI() function -decodeURI() 函數用於解碼URI,即將特殊字元轉換回原始URI 語言。

  • decodeURIComponent( ) 函數 - 此函數將完整的 URL 解碼回其原始形式。 decodeURI 僅解碼 URI 部分,而此方法解碼 URL,包括網域名稱。

語法

decodeURI(encoded_URI )
decodeURIComponent(encoded_URL
登入後複製

參數

  • #encoded_URI URI - 它接受由encodeURI()函數創建的編碼URL的輸入。

  • encoded_URL URL - 它接受由encodeURIComponent()函數建立的編碼URL的輸入。

這些函數將會傳回編碼 URL 的解碼格式。

範例 2

在下面的範例中,我們使用decodeURI()和decodeURIComponent()方法將編碼 URL 解碼為它的編碼 URL。原始形式。

#index.html

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Encode & Decode URL</title>
</head>
<body>
   <h1 style="color: green;">
      Welcome To Tutorials Point
   </h1>
   <script>
      const url="https://www.tutorialspoint.com/search?q=java articles";
      const encodedURI = encodeURI(url);
      document.write(&#39;<h4>Encoded URL: </h4>&#39; + encodedURI)
      const encodedURLComponent = encodeURIComponent(url);
      document.write(&#39;<h4>Encoded URL Component: </h4>&#39; + encodedURLComponent)
      const decodedURI=decodeURI(encodedURI);
      document.write(&#39;<h4>Decoded URL: </h4>&#39; + decodedURI)
      const decodedURLComponent = decodeURIComponent(encodedURLComponent);
      document.write(&#39;<h4>Decoded URL Component: </h4>&#39; + decodedURLComponent)
   </script>
</body>
</html>
登入後複製
輸出

如何在 JavaScript 中对 URL 进行编码和解码?#

以上是如何在 JavaScript 中對 URL 進行編碼和解碼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!