How do I replace the user input in text box as it is being typed

I have a textbox where I need to replace the user input with an int from 0 to 1 for each letter typed, so typing “hello world” for example would result in a number like “01011010100”. My code so far is:

textbox.addEventListener("beforeinput", function() {
    textbox.value = textbox.value.replace(/D+/g, findRandom());
}, false);

where findRandom() is a function that gives the random integer, and it works ok for the most part, however it does not consider the last letter typed, and using a keydown listener has too much of a lag between the letter being inputted and it being replaced. How do I make it so that no matter what the user types it comes out as 1 or 0 fast enough that they don’t see what they actually typed?