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.
Syntax
encodeURIComponent(uriComponent);
Parameters
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.
Example
const str1 = "Iron & Man";
const str2 = "Thor Love & Thunder";
const url = "https://javascript.com/test.asp?name=tony&age=34&proffession=coder";
console.log("str1 : ", encodeURIComponent(str1));
console.log("str2 : ", encodeURIComponent(str2));
console.log("url : ", encodeURIComponent(url));
Output
str1 : Iron%20%26%20Man
str2 : Thor%20Love%20%26%20Thunder
url : https%3A%2F%2Fjavascript.com%2Ftest.asp%3Fname%3Dtony%26age%3D34%26proffession%3Dcoder
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

Niva Shah is a Software Engineer with over eight years of experience. She has developed a strong foundation in computer science principles and a passion for problem-solving.