How to prevent HTML and script injections in JavaScript?

Sometimes, we want to prevent HTML and script injections in JavaScript.

In this article, we’ll look at how to prevent HTML and script injections in JavaScript.

How to prevent HTML and script injections in JavaScript?

To prevent HTML and script injections in JavaScript, we escape the string with the JavaScript code.

For instance, we write

const escapedHtml = html.replace(/</g, "&lt;").replace(/>/g, "&gt;");

to call replace to replace the opening and closing brackets with "&lt;" and "&gt;" respectively with replace.

The g flag will make replace replace all matches.

The escaped string is returned and the string won’t have valid code so it can’t be run.

Conclusion

To prevent HTML and script injections in JavaScript, we escape the string with the JavaScript code.