How to escape special characters in JavaScript?

An escape character serves as a valuable tool that empowers you to display characters that might otherwise pose challenges due to their special interpretations by browsers. This mechanism allows you to present characters that hold distinctive meanings or formatting in a manner that aligns with your original intent, overcoming potential discrepancies in interpretation between your design and the browser's rendering.

Method-1: Escape HTML special chars in JavaScript

The following code shows that the simple and easy method to escape HTML special chars in JavaScript.

var escape = document.createElement('textarea'); function escapeHTML(html) { escape.textContent = html; return escape.innerHTML; }
Full Source | JavaScript
<!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var escape = document.createElement('textarea'); function escapeHTML(html) { escape.textContent = html; return escape.innerHTML; } var escString = "////<h1>My HTML STRING</h1><p>It has html characters & such in it.</p>"; let x = escapeHTML(escString); document.getElementById("demo").innerHTML = x; </script> </body> </html>

Method-2: Escape all special characters in JavaScript

In this method, use HTML the DOM createTextNode() Method to escape HTML special chars in JavaScript.

var text_node = document.createTextNode(escString); var elem = document.getElementById('demo'); elem.appendChild(text_node);
Full Source | JavaSxript
<!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var escString = "#&&////<h1>Second method</h1><p>It has html characters & such in it.</p>"; var text_node = document.createTextNode(escString); var elem = document.getElementById('demo'); // Optional: clear its old contents elem.innerHTML = ''; elem.appendChild(text_node); </script> </body> </html>

Method-3: Escaping special characters in JavaScript

In this method, use the JavaScript replace() method to escape special characters in JavaScript.

function escapeHtml (string) { return String(string).replace(/[&<>"'`=\/]/g, function (s) { return entityMap[s]; }); }
Full Source | JavaScript
<html> <body> <p id="demo"></p> <script> var entityMap = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', '/': '/', '`': '`', '=': '=' }; function escapeHtml (string) { return String(string).replace(/[&<>"'`=\/]/g, function (s) { return entityMap[s]; }); } var escString = "////<h1>Third Method</h1><p>It has html characters & such in it.</p>///"; let x = escapeHtml(escString); document.getElementById("demo").innerHTML = x; </script> </body> </html>

JavaScript Escape Characters

example
alert("This is a test for "escape" character");

When you run the above code, it will end in an error because the browser encounters the first double quote , it will think that the string has finished.

Using escape character

alert("This is a test for \"escape\" character");

The above code will run successfully, because the browser encounters the backslash , it knows not to try to interpret the next character.

JavaScript uses the \(backslash) as an escape characters for:

  1. \' single quote

  2. \" double quote

  3. \ backslash

  4. \n new line

  5. \r carriage return

  6. \t tab

  7. \b backspace

  8. \f form feed

  9. \v vertical tab (IE < 9 treats '\v' as 'v' instead of a vertical tab ('\x0B'). If cross-browser compatibility is a concern, use \x0B instead of \v.)

  10. \0 null character (U+0000 NULL) (only if the next character is not a decimal digit; else it’s an octal escape sequence)

Conclusion

Escaping special characters in JavaScript involves using backslashes before characters that could be misinterpreted by the browser's rendering. This prevents unintended behavior and ensures the accurate representation of characters with special meanings, such as quotes or line breaks. By employing escape characters, you safeguard against potential discrepancies in interpretation and ensure the proper display of your content.