Categories
JavaScript Answers

How to sanitize user input before adding it to the DOM in JavaScript?

Spread the love

Sometimes, we want to sanitize user input before adding it to the DOM in JavaScript.

In this article, we’ll look at how to sanitize user input before adding it to the DOM in JavaScript.

How to sanitize user input before adding it to the DOM in JavaScript?

To sanitize user input before adding it to the DOM in JavaScript, we use the string replace method.

For instance, we write

const sanitize = (string) => {
  const map = {
    "&": "&",
    "<": "&lt;",
    ">": "&gt;",
    '"': "&quot;",
    "'": "&#x27;",
    "/": "&#x2F;",
  };
  const reg = /[&<>"'/]/gi;
  return string.replace(reg, (match) => map[match]);
};

to call string.replace with reg and a callback to replace the characters to be escaped with the corresponding HTML entities.

reg matches all values since it has the g flag.

And the i flag makes replace match in a case-insensitive manner.

Conclusion

To sanitize user input before adding it to the DOM in JavaScript, we use the string replace method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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