How to Escape HTML in JavaScript?

Estimated read time 1 min read

You can escape HTML in JavaScript using the .replace() method and a regular expression.

Here’s an example:

let str = '<h1>Hello, World!</h1>';

str = str.replace(/[&<>"']/g, function(m) {
  return {
    '&': '&',
    '<': '<',
    '>': '>',
    '"': '"',
    "'": '''

console.log(str); // Output: '<h1>Hello, World!</h1>'

In this example, the .replace() method is called on the string str. The first parameter to the method is a regular expression that matches the characters &, <, >, ", and '. The second parameter is a function that takes the matched character as its argument and returns the corresponding HTML entity. This function uses an object literal to map characters to entities.

The g flag in the regular expression makes the .replace() method perform a global search, so all occurrences of the characters are replaced.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply