如何在 JavaScript 中对 URL 进行编码和解码?
任何网站的 URL 都需要对 URI 和 URI 组件进行编码和解码,以到达或重定向用户。这是 Web 开发中的一项常见任务,通常是在使用查询参数向 API 发出 GET 请求时完成的。查询参数还必须编码在 URL 字符串中,服务器将对其进行解码。许多浏览器会自动对 URL 和响应字符串进行编码和解码。
例如,空格“ ”被编码为 + 或 %20。
对 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('<h4>URL: </h4>' + url)
const encodedURI=encodeURI(url);
document.write('<h4>Encoded URL: </h4>' + encodedURI)
const encodedURLComponent=encodeURIComponent(url);
document.write('<h4>Encoded URL Component: </h4>' + encodedURLComponent)
</script>
</body>
</html>
输出
解码 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('<h4>Encoded URL: </h4>' + encodedURI)
const encodedURLComponent = encodeURIComponent(url);
document.write('<h4>Encoded URL Component: </h4>' + encodedURLComponent)
const decodedURI=decodeURI(encodedURI);
document.write('<h4>Decoded URL: </h4>' + decodedURI)
const decodedURLComponent = decodeURIComponent(encodedURLComponent);
document.write('<h4>Decoded URL Component: </h4>' + decodedURLComponent)
</script>
</body>
</html>
输出
以上就是如何在 JavaScript 中对 URL 进行编码和解码?的详细内容,更多请关注双恒网络其它相关文章!



