Strip HTML from all user-submitted inputs using military grade regex, whether you print them on screen on not.

Enter your username:

Enter your username:
  <input type="text" id="input"/>
  <div id="screen"></div>

document.querySelector('#input').addEventListener('keyup', function(e) {
  if (e.keyCode === 13) {
    const username = document.querySelector('#input').value.replace(/(<([^>]+)>)/, '');
    const tagString = `<div data-user=${username}>😉 Not today, ${username}!</div>`;
    const range = document.createRange();
    const documentFragment = range.createContextualFragment(tagString);
#input {
  font-size: 16px;
  height: 26px;
  width: 100%;
  margin-bottom: 10px;
  padding: 20px;
.applet-html {
  padding: 20px;
.applet {
  margin-bottom: 20px;

Takeaways and notes#

  • You don't need to print any user-submitted data to the screen to cause XSS
  • If you are writing a user-submitted input to the DOM, you could be vulnerable to XSS
  • Eg: "<x>onmouseover=alert(1)>
Tweet this | Share on LinkedIn |