javascriptinputfrontendimaskjs

Replace underscores on typing number input in JavaScript


I have a text field with little underscores as (_________). How do I use JavaScript to make these dashes to be replaced by the input number upon typing? (48721____) As I type, I want the underscore to be replaced with the number I type. How do I achieve this?


Solution

  • You can do something like this:

    const p = document.querySelector("p")
    const amountOfDashes = 10
    p.textContent = "_".padEnd(amountOfDashes, "_")
    document.addEventListener("keydown", e => {
        if(e.key === "Backspace") {
            const pattern = /\d(?!\d)/;
            if(!pattern.test(p.textContent)) return;
            p.textContent = p.textContent.replace(pattern, "_");
            return;
        }
        const val = parseInt(e.key);
        if(isNaN(val)) return;
        p.textContent = p.textContent.replace("_", val);
    })
    

    Tell me if this solves your problem.