OneBite.Dev - Coding blog in a bite size

escape a string in Javascript

Code snippet on how to escape a string in Javascript

  function escapeString(str) {
    return str.replace(/[&'"<>\/]/g, function(char) {
      return '&#' + char.charCodeAt(0) + ';';
    });
  }

This code is used for escaping strings in Javascript. It has one parameter called ‘str’ that refers to the string which is being escaped. The return statement uses the string’s replace method to find and replace characters that need to be escaped with the HTML entity they correspond to. The regular expression in the parameter looks for characters that need to be escaped such as the ampersand, single quote, double quote, less than sign, greater than sign, or forward slash. Whenever any of these characters is found, it calls the anonymous function which returns a entity of the character, using the charCodeAt() method of the string object, which returns the unicode value of the character. This will make sure that the strings are escaped properly in HTML.

javascript