How to encode and decode a URL in JavaScript?

05-May-2023

.

Admin

How to encode and decode a URL in JavaScript?

Today, encode and decode url javascript is our main topic. this example will help you how to encode and decode a url in javascript. if you want to see example of encode url in javascript then you are a right place. This post will give you simple example of javascript decodeuri() method. follow bellow step for decoding url parameters with javascript.

To encode a URL in JavaScript, you can use the `encodeURIComponent()` function. This function takes a string as input and returns a URI-encoded version of that string.

Example 1:


<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How to encode and decode a URL in JavaScript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

const url = "https://www.example.com/search?q=JavaScript tutorial";

const encodedUrl = encodeURIComponent(url);

console.log(encodedUrl); // output: "https%3A%2F%2Fwww.example.com%2Fsearch%3Fq%3DJavaScript%20tutorial"

</script>

</html>

To decode a URL in JavaScript, you can use the `decodeURIComponent()` function. This function takes a URI-encoded string as input and returns the decoded version of that string.

Example 2:

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How to encode and decode a URL in JavaScript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

const encodedUrl = "https%3A%2F%2Fwww.example.com%2Fsearch%3Fq%3DJavaScript%20tutorial";

const decodedUrl = decodeURIComponent(encodedUrl);

console.log(decodedUrl); // output: "https://www.example.com/search?q=JavaScript tutorial"

</script>

</html>

#JavaScript