In this post, we will see how to escape ampersand in JavaScript.
To escape Ampersand in JavaScript, use encodeURIComponent()
in JavaScript.
1 2 3 4 |
var ampersand = encodeURIComponent('&'); console.log(ampersand); |
Output
1 2 3 |
%26 |
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
1 2 3 4 |
var link = 'http://example.com?company_name=' + encodeURIComponent('A&B'); console.log(link); |
Output
1 2 3 |
http://example.com?company_name=A%26B |
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.
1 2 3 4 |
var link = 'http://example.com?company_name=' + encodeURIComponent('A&B>< '); console.log(link); |
Output
1 2 3 |
htp://example.com?company_name=A%26B%3E%3C%20 |
As you can see that we were able to successfully escape all special characters using encodeURIComponent()
.