Signup/Sign In
LAST UPDATED: AUGUST 4, 2021

How to encode URL in JavaScript?

Answer: Using encodeURI() and encodeURIComponent() method

In this lesson, we are going to learn how to encode the URL using JavaScript. So there are two built-in methods offered by JavaScript that help to encode the URL, these methods are:

  • encodeURI() method
  • encodeURIComponent() method

Let's discuss both methods in detail

Using encodeURI() method

The encodeURI() method is used to encode the URI. This function encode all the special characters except , / ? : @ & = + $ #.

Example: Using encodeURI() method

In the given example, we have encoded the URL using encodeURI() method.

<!DOCTYPE html>
<html>
<head>
	<title>Encode URL</title>
</head>
<body>
	<button onclick="myFunction()">Click here</button>
	<p id="demo"></p>
	<script>
		function myFunction() {
		var uri = "https://www.studytonight.com/";
		var result = encodeURI(uri);
		document.getElementById("demo").innerHTML = result;
		}
	</script>
</body>
</html>

Output

encode

Using encodeURIComponent() method

We can encode URL in JavaScript using encodeURIComponent() method. This method encodes the URI components. It replaces each instance of a certain character with one two or three or four escape sequences representing the UTF-8 encoding of the character.

This function encodes special characters, these characters are , / ? : @ & = + $ #.

Example: Using encodeURIComponent() method

In the given example, we have used the encodeURIComponent() method to encode the given URL.

<!DOCTYPE html>
<html>
<head>
	<title>Encode URL</title>
</head>
<body>
	<button onclick="myFunction()">Click Here</button>
	<p id="demo"></p>
	<script>
		function myFunction() {
		  var url = "https://www.studytonight.com/";
		  var encode = encodeURIComponent(url);
		  document.getElementById("demo").innerHTML = encode;
		}
	</script>
</body>
</html>

Output

encode

Conclusion

In this lesson, we have learned how to encode the URL in JavaScript. Basically, there are two built-in methods offered by JavaScript which allow us to encode the URL, these methods are encodeURI() and encodeURIComponet() method. Both the method functions same but there is a slight difference in both. The encodeURI() method does not encode the special characters while the encodeURIComponent() method does.



About the author: