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.
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:
- \' 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)
Related Topics
- JavaScript Interview Questions (Part2)
- JavaScript Interview Questions (Part3)
- Is JavaScript a true OOP language?
- Advantages and Disadvantages of JavaScript
- Difference Between JavaScript and ECMAScript?
- What is noscript tag?
- What is undefined x 1 in JavaScript?
- JavaScript : Logical Operators
- Difference between '=', '==' and '===' operators?
- How to reload a page using JavaScript?
- How to write html code dynamically using JavaScript?
- How to add html elements dynamically with JavaScript?
- How to load another html page from javascript?
- What Is The Disadvantages Using InnerHTML In JavaScript?
- What is Browser Object Model
- How to detect the OS on the client machine in JavaScript?
- Difference between window, document, and screen in Javascript?
- Difference between the substr() and substring() in JavaScript?
- How to replace all occurrences of a string in JavaScript?
- How to test a string as a literal and as an object ?
- What is Associative Array? How do we use it?
- What is an anonymous function in JavaScript?
- What is the use of 'bind' method in JavaScript?
- Pure functions Vs. Impure functions in javascript
- Is Javascript a Functional Programming Language?
- What's the Difference Between Class and Prototypal Inheritance?
- Javascript, Pass by Value or Pass by Reference?
- How to prevent modification of an object in Javascript?
- What is 'this' keyword in JavaScript?
- How Does Function Hoisting Work in JavaScript?
- What do mean by NULL in Javascript?
- What does the delete operator do in JavaScript?
- What is the Infinity property used for in Javascript?
- Event bubbling and Event Capturing in JavScript?
- What is "strict mode" and how is it used in JavaScript?
- What is the difference between .call() and .apply()?
- Entire content of a JavaScript source file in a function block?
- What is an immediately-invoked function expression?
- What is escape & unescape String functions in JavaScript?
- What is the instanceof operator in JavaScript?
- What Are RESTful (REpresentational State Transfer)Web Services?
- What is Unobtrusive JavaScript & Why it's Important?
- What Does JavaScript Void(0) Mean?
- What are JavaScript Cookies?
- Difference between Client side JavaScript and Server side JavaScript
- TypeError: document.getelementbyid(...) is null
- Uncaught TypeError: Cannot read property of undefined In JavaScript
- What's the difference between Null and Undefined?