Skip to content

JavaScript escape special characters | Example code

  • by

You can try replacing them with a given list of char using replace() method and Regex in JavaScript.

How to JavaScript escape special characters example

Example code of JavaScript function to escapes special characters (&, <, >, ‘, “) for use in HTML.

<!DOCTYPE html>
<html>
<body>

  <script>


    function escape_html(str) {

     if ((str===null) || (str===''))
       return false;
     else
       str = str.toString();

     var map = {
      '&': '&amp;',
      '<': '&lt;',
      '>': '&gt;',
      '"': '&quot;',
      "'": '&#039;'
    };

    return str.replace(/[&<>"']/g, function(m) { return map[m]; });
  }

  console.log(escape_html('SQL & MySQL'));
  console.log(escape_html('10 > 2'));
</script>
</body>
</html>

Output:

JavaScript escape special characters

Another example

function escapeRegExp(input) {
	const source = typeof input === 'string' || input instanceof String ? input : '';
	return source.replace(/[-[/\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}

More example


// Vanilla JS
function escapeRegex(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

// Or with npm: npm install escape-string-regexp
const escapeRegex = require('escape-string-regexp');

// Usage:
const regex = new RegExp(escapeRegex('How much $ is that?'));

Do comment if you have any doubts or suggestions on this JS escape topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *