Escape Ampersand in URL in JavaScript

In this post, we will see how to escape ampersand in JavaScript.

To escape Ampersand in JavaScript, use encodeURIComponent() in JavaScript.

Output

As you can see that when we called encodeURIComponent, it encoded & to %26.

You can use % to escape characters that aren’t allowed in URLs. Here & is 26 in Hexadecimal and that’s the reason encodeURIComponent() converted & to %26.

Let’s see with the help of simple example:

Let’s say company_name is A&B and url is:

http://example.com?company_name=A&B

if don’t escape &, then you won’t get expected result.

To escape & character, you can use encodeURIComponent() as below

Output

As you can see, we have successfully escape ampersand in URL.

Generic solution to escape special character in JavaScript

Great thing about our solution is that it will work with any special character and you can same solution.

Output

As you can see that we were able to successfully escape all special characters using encodeURIComponent().

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *