How to escape special characters in JavaScript?
An escape character enables you to output characters you wouldn't normally be able to, usually because the browser will interpret it differently to what you intended.
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.
Full Source | JavaScript
Method-2: Escape all special characters in JavaScript
In this method, use HTML the DOM createTextNode() Method to escape HTML special chars in JavaScript.
Full Source | JavaSxript
Method-3: Escaping special characters in JavaScript
In this method, use the JavaScript replace() method to escape special characters in JavaScript.
Full Source | JavaScript
JavaScript Escape Characters
example
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
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:
- \' single quote
- \" double quote
- \ backslash
- \n new line
- \r carriage return
- \t tab
- \b backspace
- \f form feed
- \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.)
- \0 null character (U+0000 NULL) (only if the next character is not a decimal digit; else it’s an octal escape sequence)