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 &amp; MySQL"
console.log(escape_html('3 > 2'));
"3 &gt; 2"

Sample Solution:

JavaScript Code:

function escape_html(str) {
 if ((str===null) || (str===''))
       return false;
   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'));


PHP &amp; MySQL 
3 &gt; 2


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: JavaScript: Escapes special characters for use in HTML

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.

Follow us on Facebook and Twitter for latest update.