Home > Article > Web Front-end > How to encode and decode URLs in JavaScript?
The URL of any website requires encoding and decoding of the URI and URI components in order to reach or redirect the user. This is a common task in web development and is typically done when making a GET request to an API using query parameters. The query parameters must also be encoded in the URL string, which will be decoded by the server. Many browsers automatically encode and decode URL and response strings.
For example, a space " " is encoded as or .
encodeURI() function - The encodeURI() function is used to encode the complete URI, that is, convert the special characters in the URI into a language that the browser can understand. Some unencoded characters are: (, / ? : @ & = $ #).
encodeURIComponent() function - This function encodes the entire URL instead of just the URI. This component also encodes the domain name.
encodeURI(complete_uri_string ) encodeURIComponent(complete_url_string )
##complete_uri_string string - It holds the URL to be encoded.
complete_url_string string - It holds the complete URL string to be encoded.
# 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>Output
##Decoded URL
The -decodeURI() function is used to decode a URI i.e. convert special characters back to the original URI language.
- This function decodes the complete URL back to its original form. decodeURI decodes only the URI part, whereas this method decodes the URL, including the domain name.
decodeURI(encoded_URI ) decodeURIComponent(encoded_URL
These functions will return the decoded format of the encoded 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>Output
The above is the detailed content of How to encode and decode URLs in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!