Home > Web Front-end > JS Tutorial > Encode URL using encodeURI function in JavaScript

Encode URL using encodeURI function in JavaScript

WBOY
Release: 2023-11-18 10:37:55
Original
1145 people have browsed it

Encode URL using encodeURI function in JavaScript

Use the encodeURI function to encode the URL in JavaScript. We can demonstrate it through the following code example:

// 原始URL
const urlString = "https://www.example.com/路径/文件.html?参数=值&参数2=值2";

// 使用encodeURI函数对URL进行编码
const encodedUrlString = encodeURI(urlString);

// 输出编码后的URL
console.log(encodedUrlString);
Copy after login

In the above code, we use the encodeURI function to encode the example. The URL is encoded. The encodeURI function will convert special characters (such as spaces, #, %, etc.) in the URL into the corresponding encoding form to ensure that the URL can be transmitted correctly and recognized by the server.

In the above code, the original URL is "https://www.example.com/path/file.html?parameter=value¶meter2=value2". By calling the encodeURI function, we obtain the encoded URL string, namely "https://www.example.com/path/file.html?parameter=value¶meter2=value2".

It should be noted that the encodeURI function only encodes some special characters in the URL and does not encode the entire URL. If we need to encode the entire URL, we can use the encodeURIComponent function.

Here is a similar code example that uses the encodeURIComponent function to encode the entire URL:

// 原始URL
const urlString = "https://www.example.com/路径/文件.html?参数=值&参数2=值2";

// 使用encodeURIComponent函数对URL进行编码
const encodedUrlString = encodeURIComponent(urlString);

// 输出编码后的URL
console.log(encodedUrlString);
Copy after login

In the above code example, we use the encodeURIComponent function to encode the entire URL. The encodeURIComponent function will convert all characters in the URL into the corresponding encoding form to ensure that the URL can be transmitted correctly.

Summary: Use the encodeURI function to encode special characters in the URL, and use the encodeURIComponent function to encode the entire URL. According to actual needs, we can choose a suitable function to encode the URL to ensure the correctness and usability of the URL.

The above is the detailed content of Encode URL using encodeURI function in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template