URL is the address to access Internet resources. Each URL points to a unique resource on the network. The URL may sometimes contain special characters or require dynamic operations.
In this article, we will explore modern techniques for handling URLs in JavaScript and answer questions related to encoding and decoding URLs in JavaScript.
When you enter content in a browser, one or more search results are provided. The format of these search results is confusing, including text and special characters such as %, +, ?, =, &, <, >, etc.
Using URLs in JavaScript
Before we start encoding and decoding a URL, we need to learn how to use URLs in JavaScript. This is very useful when you need to build, parse, and manipulate URLs. Modern JavaScript provides a built-inURL
class, which provides the powerful function of handling URLs:
- Create a URL object:To use a URL in JavaScript, you can use this URL syntax to create a URL object.
const url = new URL("/editor?q=hello world");
Access URL components:Once you have a URL object, you can access various components of the URL. The following components are accessible:
-
: A protocol that returns the URL (for example "https:")
-
: Returns the hostname of the URL (for example "")
-
: Return the path to the URL (for example, "/editor")
-
: Returns the URLSearchParams object containing the query parameters
(); // Output: https: (); // Output: (); // Output: /editor (); // Output: q=hello+world
-
Convert a URL object or component to a string:Can be used
toString()
The JavaScript method gets the URL, or in this case the URL component in the form of a string.
(()); // Output: q=hello+world
-
Get the current page URL: To get the current URL of the current web page, please use this
property.
const currentUrl = ; (currentUrl);
-
Modify URL components:
searchParams
The URL's query parameters can be easily modified using the properties of the URL object.
("q", "new query"); (()); // Output: q=new+query
This will update the value of the 'q' query parameter from 'hello world' to 'new+query' in encoded format.
- Construct a new URL:You can also construct new URLs by combining different components or modifying existing components.
const newURL = new URL(""); = "/new-path"; ("q", "new query"); (()) // Output: /new-path?q=new+query
The above line of code first creates a URL object, sets the path name, and then sets the query parameters to construct a new URL. It then converts the result to a string for easy reading.
Try running all the code snippets provided above to learn how to use URLs in JavaScript.
Now that we have learned how to use URLs in JavaScript, we will learn how to encode and decode URLs in JavaScript.
Encoding URLs in JavaScript
Encoding a URL essentially means converting special characters in the URL into a format that can be transferred correctly on the Internet.
This process is necessary because certain characters in the URL, such as spaces or symbols, may have unique meanings, and encoding them ensures that the browser and web server interpret them correctly.
Now, why do you need to encode the URL? This is because by default, the characters that URLs can contain are limited. The standard URL specification specifies that a URL can only contain characters from the ASCII character set, which consists of 128 characters. These characters include upper and lowercase letters, numbers, and limited special characters such as "-", "_", "." and "~".
Reserved characters have specific meanings in the URL and do not belong to the standard ASCII set and must be encoded if used in the URL. The reserved characters include "/", "[", "]", "@", "%", ":", "&", "#", "@", "=", ", etc.
To include reserved characters in the URL, they must be encoded in percentage terms, meaning they are replaced by a percent sign ("%"), followed by their hexadecimal value. For example, since the URL cannot contain spaces, the space character (" ") is encoded as "%20" or "+" and the symbol ("&") is encoded as "%26".
JavaScript provides two functions that encode URLs:encodeURI()
andencodeURIComponent()
。
Function encodeURIComponent()
ShouldencodeURIComponent()
Functions encode URI components (such as query parameters) where certain characters have special meanings and must be encoded. It encodes all characters except the standard ASCII alphanumeric characters (AZ, az, and 0-9), hyphen ("-"), underscore ("_"), period ("."), and wavy characters ("~").
Take a look at the following code snippet and its results:
const url = ""; const encodedURL = encodeURIComponent(url); (encodedURL); // Output: https%3A%2F%
In the first example, we define a variable "url" and assign a value to it. We call thisencodedURIComponent()
function, and pass "url" as an argument. The function then encodes the URL by replacing a specific character with a percentage encoding representation and records it to the terminal.
Characters such as ':' and '/' have been replaced with their percentage-encoded representations (%3A and %2F, respectively).
const url2 = "mango & pineapple"; const encodedURL2 = encodeURIComponent(url2); (encodedURL2); // Output: mango%20%26%20pineapple
In Example 2, can you see the "%20" and "%26" symbols representing the space and the θ (&) characters? The passed value is not a URL, but it is a good example of how JavaScript encodes spaces and versus numbers.
About thisencodeURIComponent()
For more information about functions, seeMDN Documentation。
Function encodeURI()
ShouldencodeURI
Functions are used to encode the entire URI, including the entire URL. It does not encode certain characters allowed in the URI, such as letters, numbers, hyphens, periods, and underscores.
Uncoded characters andencodeURI
The function has the same charactersencodeURIComponent
, plus a few, i.e.:
- question mark("?")
- hashtag("#")
- Dollar sign ("$")
- with number ("&")
- comma(",")
- Forward slash ("/")
- colon (":")
- semicolon(";")
- symbol("@")
- equal sign ("=")
- Plus sign ("+")
Let's look at some code snippets.
const url = ''; (encodeURI(url)); // Output:
The result is the same as the given URL because theencodeURI()
Functions do not encode certain characters such as slashes, periods, and colons.
ifencodeURIComponent()
Used in the same example, it will be observed that some characters have been encoded. Let's try it out.
const url = ''; (encodeURIComponent(url)); // Output: https%3A%2F%
Now, for more complex code examples, the value of the URL to be encoded is the query parameter.
const url = "/search?q=hello world"; (encodeURI(url)); // Output: "/search?q=hello%20world" (encodeURIComponent(url)); // Output: https%3A%2F%%2Fsearch%3Fq%3Dhello%20world
ShouldencodeURI()
The function simply encodes the space characters in the query input to "%20". On the other hand,encodeURIComponent()
Encode colon, slash and space characters in query parameters.
About thisencodeURI()
For more information about functions, seeMDN Documentation。
The key to understanding the difference between these two functions is to pay attention to which characters are encoded and which characters are not encoded. Although they are slightly different, they all do the same - encode the URL to make it easier to transfer over the internet.
Reasons for encoding the URL
- Safety and accuracy:The URL may contain special characters, such as spaces or query parameters, which may be misunderstood by the web server or browser. Encoding the URL ensures that special characters are interpreted correctly, reducing errors and ensuring accurate transmission.
- Data Integrity:When sending data in a URL (such as a search query or form submission), encoding ensures that the data is retained during transmission. Decoding allows the receiver to process and interpret the data correctly.
Decode URLs in JavaScript
Decoding is the opposite of encoding. It restores the effect of encoded URLs.
The decoding URL requires converting the percentage-encoded characters back to their original form. Decoding is important when an encoded URL is received and information needs to be extracted from it, which is similar to solving a difficult problem where it must be decoded to receive messages.
Function decodeURIComponent()
In JavaScript, you can use this function to decode the URLdecodeURIComponent()
. When this function is called to decode the URL, it decodes each component of the URI.
const encodedURL = "https%3A%2F%%2Fsearch%3Fq%3Dhello%20world"; (decodeURIComponent(encodedURL)); // Output: "/search?q=hello world"""
Here,decodeURIComponent()
The function takes the encoded URL as input and returns the decoded URL.
thisMDN DocumentationMore information about this feature is provided.
Function decodeURI()
ShoulddecodeURI()
Functions are used to decode the entire URI, including domains, paths, and query parameters.
const url = "/search?q=hello world"; (encodeURI(url)); // Output: /search?q=hello%20world (decodeURI(url)); // Output: /search?q=hello world
In the example above, we use this function to encode the URL query parametersencodeURI()
, and use thisdecodeURI()
The function decodes the encoded URL.
CheckMDN DocumentationTo get thedecodeURI()
More information about the method.
It is one thing to learn how to encode and decode URLs in JavaScript; it is one thing to learn how to encode and decode URLs in JavaScript. Knowing when to encode and decode a URL is another matter.
When to encode a URL
Here are some common scenarios that may require encoding URLs:
- Generate dynamic URL:If the application generates a URL dynamically (such as generating links based on user input or database values), make sure any user-generated input is correctly encoded. This ensures that any special characters in the URL are converted to a format that can be safely transferred over the Internet.
const dynamicValue = "hello world"; const encodedURL = "/search?q=" + encodeURIComponent(dynamicValue); (encodedURL); // Output: "/search?q=hello%20world"
- Use URL parameters to process form submissions:When a user submits form data (such as a user profile), form data is usually included in the URL as a query parameter. If it contains special characters (such as &, ?, or space), it should be encoded before sending the URL parameter via GET or POST request. This prevents unexpected behavior or errors due to invalid characters in the URL and ensures safe transfer of data.
<form action="/search"> <input type="text" name="q" value="hello world"> <input type="submit" value="Search"> </form>
- When the Submit button is clicked, the form submits the data to "https:////search".
- The form data is encoded using the GET method and sent to the server because it is the default method for form submission when the action attribute is specified.
- The first input field contains the value "hello world". After submitting the form, the value will be encoded and appended to the URL as a query parameter. For example, the encoded URL might look like "https:////search?q=hello%20world".
- Send data via Ajax request:When sending an Ajax request to retrieve data from the server, parameters are usually included in the URL. These parameters may contain special characters, so it is necessary to encode the URL to ensure that Ajax requests work properly and avoid unexpected problems caused by special characters.
const inputWord = "hello world"; const encodedInputWord = encodeURIComponent(inputWord); const url = "https:////api/search?q=" + encodedInputWord; JAVASCRIPT
When to decode the URL
Here are some common scenarios where URLs may need to be decoded:
- Process URLs received from external sources:External sources (such as API responses, user input) can provide encoded URLs. Decoding these URLs allows extracting the original information and ensuring that the data is interpreted correctly.
const encodedURL = "https%3A%2F%%2Fsearch%3Fq%3Dhello%20world"; const decodedURL = decodeURIComponent(encodedURL); (decodedURL); // Output: "/search?q=hello world"
- Show URL in the user interface:When displaying URLs in the application's user interface, make sure they are in a primitive, human-readable format. Decoding URLs ensures that they are displayed correctly to the user.
const encodedURL = "https%3A%2F%%2Fsearch%3Fq%3Dhello%20world"; const decodedURL = decodeURIComponent(encodedURL); ("url").textContent = decodedURL; // Output on the browser UI: "/search?q=hello world"
URL encoding and decoding tools
In addition to the built-in functions used to encode and decode URLs in most programming languages, online tools are available for performing basic encoding and decoding operations. Examples of such tools include, and gochyu url encode.
These tools are simple to use: enter the URL you want to encode or decode and you can get the results.
in conclusion
In short, understanding the concepts of URL encoding and decoding is crucial for any web developer. These processes ensure data integrity, security and accuracy when data is transmitted over the Internet. Understanding when and how to encode or decode a URL can help developers develop secure and reliable web applications that effectively handle URL-related tasks.
The above is a detailed explanation of URL encoding and decoding in JavaScript. For more information about JavaScript URL encoding and decoding, please pay attention to my other related articles!