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

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;",
    "'": "'",
    "/": "/",
  };
  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.