Introduction

Have you ever come across a URL encoded string and needed to decode it in JavaScript? URL encoding is a way of converting special characters into a format that can be safely transmitted over the internet. In this tutorial, we will explore how to decode a URL string in JavaScript, allowing you to extract the original information.

To get started, we can make use of the built-in decodeURIComponent() function in JavaScript. This function decodes a URI component that has been encoded with the encodeURIComponent() function or a similar method.

Here’s an example of how to use decodeURIComponent():

const encodedString = ""Hello%20World%21"";
const decodedString = decodeURIComponent(encodedString);

console.log(decodedString);
// Output: Hello World!

In the example above, we have an encoded string ""Hello%20World%21"". The %20 represents a space character, and %21 represents an exclamation mark. After applying decodeURIComponent(), the decoded string ""Hello World!"" is printed to the console.

If you have an entire URL that needs to be decoded, you can use the decodeURI() function instead. This function decodes the entire URI, including the protocol, domain, and path.

Let’s see an example of decodeURI() in action:

const encodedURL = ""https%3A%2F%2Fwww.example.com%2Fpath%2Fpage.html"";
const decodedURL = decodeURI(encodedURL);

console.log(decodedURL);
// Output: https://www.example.com/path/page.html

In the above example, we have an encoded URL ""https%3A%2F%2Fwww.example.com%2Fpath%2Fpage.html"". After applying decodeURI(), the decoded URL ""https://www.example.com/path/page.html"" is printed to the console.

It’s worth noting that both decodeURIComponent() and decodeURI() can throw an error if the input string is not a valid encoded URI component or URI respectively. To handle this, you can wrap the decoding logic in a try...catch block.

try {
  const decodedString = decodeURIComponent(encodedString);
  console.log(decodedString);
} catch (error) {
  console.error(""Invalid encoded string:"", error);
}

Now that you understand how to decode URL strings in JavaScript, you can use this knowledge to extract meaningful information from encoded URLs or handle user input in a safe and reliable manner.

I hope you found this tutorial helpful!