JavaScript: Escapes special characters for use in HTML
JavaScript String: Exercise-31 with Solution
Write a JavaScript function to escape special characters (&, <, >, ', ") for use in HTML.
Test Data:
console.log(escape_html('PHP & MySQL'));
"PHP & MySQL"
console.log(escape_html('3 > 2'));
"3 > 2"
Sample Solution:
JavaScript Code:
function escape_html(str) {
if ((str===null) || (str===''))
return false;
else
str = str.toString();
var map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return str.replace(/[&<>"']/g, function(m) { return map[m]; });
}
console.log(escape_html('PHP & MySQL'));
console.log(escape_html('3 > 2'));
Output:
PHP & MySQL 3 > 2
Explanation:
In the exercise above,
- The function "escape_html()" is defined to escape HTML special characters in a given string.
- It checks if the input string is null or empty. If it is, the function returns false.
- If the input string is not null or empty, it converts it to a string.
- The function defines a map object that contains HTML special characters as keys and their corresponding HTML entities as values.
- It uses a regular expression to replace occurrences of HTML special characters in the string with their corresponding HTML entities using the "replace()" method.
- Finally, the function returns the modified string with HTML special characters escaped.
Flowchart:
Live Demo:
See the Pen JavaScript Escapes special characters for use in HTML - string-ex-31 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus.
Previous: Write a JavaScript function check if a string ends with specified suffix.
Next: Write a JavaScript function to remove non-printable ASCII chars.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/javascript-exercises/javascript-string-exercise-31.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics