# How to encode a URL using JavaScript function?

Front End TechnologyJavascriptWeb Development

#### BACK-END web Development with php & MySQL

10 Lectures 1 hours

#### The Complete Front-End Web Development Course!

127 Lectures 16.5 hours

#### Front End & Fullstack - React 16.8 +

Best Seller

131 Lectures 12.5 hours

As we know, a URL is a web address. What is URL encodingand why do we need to encode a URL? The process of turning a string into an accurateURL format is known as URL encoding.

A valid URL format only uses "alpha | digit | safe | extra | escape" characters. Only a limited selection of the normal 128 ASCII characters is permitted in URLs. It is required to encrypt reserved characters that are not part of this set. The reliability and security of the URLs are increased with URL encoding.

Each character that needs to be URL-encoded is encoded using the character "%" and a two-character hex value corresponding to its utf-8 character.

For example,

¥€¢£¥€¢£^°√•
will be encoded to
C2%A5%E2%82%AC%C2%A2%C2%A3%C2%A5%E2%82%AC%C2%A2%C2%A3%5E%C2%B0%E2%88%9A%E
2%80%A2


## Using the encodeURI() Method

### Syntax

encodeURIComponent(uri)


In the syntax for encodeURIComponent(), we need to send an argument which will be the url or string to be encoded.

### Example

In this example, we use a function to perform encodeURIComponent(). As we learned above, we have passed the URL string according to the working of the method.

<html>
<body>
<h2>Using the <i>encodeURIComponent()</i> method.</h2>
<p id="idEnOutput"></p>
<script>
function doEncode(str) {
var encode, dispEl, disStr = "encodeURIComponent";
dispEl = document.getElementById("idEnOutput");
encode = encodeURIComponent(str);
dispEl.innerHTML = disStr + "<br>" + encode;
}
doEncode("qstr?qtxt=me@gmail.com");
</script>
</body>
</html>


In this tutorial, we have seen the two methods to encode a URL in JavaScript.

The encodeURI() method is the best compared to the encodeURIComponent() method. Because encodeURIComponent() encodes the entire URL along with the domain name. This gives an invalid URL. Hence we can use this method only when we need to encode the characters that will not be encoded by the encodeURI() method.

Updated on 23-Aug-2022 09:12:46