JSFiddle - React, Tailwind, and code Playground

by Stephen

HTML

<p>You can't put spaces at the start:</p>
<input type="text" id="noSpaces">

JavaScript

var elmt = document.getElementById('noSpaces');

elmt.addEventListener('keydown', function (event) {
//    if (elmt.value.length === 0 && event.which === 32) {
//        event.preventDefault();
//    }
    if (event.which === 32) {
        elmt.value = elmt.value.replace(/^\s+/, '');
        if (elmt.value.length === 0) {
            event.preventDefault();
        }
    }
});