JavaScript encodeURIComponent() Guide

The encodeURIComponent() function is a built-in function in JavaScript that is used to encode strings for URLs. It is mainly used to convert special characters in a URL to their hexadecimal representation, which helps prevent errors in the URL.

Here is an example of how to use the encodeURIComponent() function:

encodeURIComponent(str)

“Where ‘str’ is the string that needs to be URL encoded.”

I would like to order the seafood platter.

Could you please bring me the seafood platter?

var url = "https://www.example.com?q=hello world";
var encodedUrl = encodeURIComponent(url);
console.log(encodedUrl);
// 输出:https%3A%2F%2Fwww.example.com%3Fq%3Dhello%20world

In the example above, the original URL had spaces and special characters. After using the encodeURIComponent() function to encode the URL, the correct URL encoding was obtained.

bannerAds