How to Escape Special Characters in JavaScript

To escape special characters in JavaScript, use the encodeURIComponent() method. The encodeURIComponent() is a built-in JavaScript function that encodes a URI by replacing each instance of certain characters with one, two, three, or four escape sequences representing the UTF-8 encoding of the character.




uri – We can pass any data types like string, number, boolean, object, etc because before escaping it will be converted into a string.

Return value

It will return a string in which special characters are escaped.


const str1 = "Iron & Man";
const str2 = "Thor Love & Thunder";
const url = "";

console.log("str1 : ", encodeURIComponent(str1));
console.log("str2 : ", encodeURIComponent(str2));
console.log("url : ", encodeURIComponent(url));


str1 : Iron%20%26%20Man
str2 : Thor%20Love%20%26%20Thunder
url :

In the above example, we escape our special characters string by using the encodeURIComponent() method.

The encodeURIComponent() method escapes all the characters except the below characters.

* ‘ ( )- _ . ! ~0-9 A-Z a-z  – These characters will not be escaped by the encodeURIComponent() method.

So in the above example, we can see encodeURIComponent replaced all the characters with UTF-8 characters or hexadecimal characters except the above characters.

Why do we need to escape special characters in JavaScript

In the url query, we don’t need any special characters like space, etc. So by using these methods we escape those characters. Which characters you must and which you mustn’t escape indeed depends on the regex flavor you’re working with.

Character escaping is what allows certain characters to be literally searched for and found in the input string.

That’s it for this tutorial.

Related posts

How to Remove First Character from String in Javascript

How to Get Last Character from String in Javascript

How to Get First Character of String in JavaScript

How to Get Character from String in Javascript

Leave a Comment