If you're writing JavaScript and need to sanitize a string, here's an easy way to do it.
const html = "<p>Test</p>";
const elm = document.createElement("p");
elm.textContent = html;
const sanitized = elm.innerHTML;
The reason this works is that when you set the potentially dangerous string to the element's textContent
property, it will be escaped. Then you just read it back using innerHTML
and you have a safe string that you can use instead.