I want to use regex like a state machine, feeding only one character at a time.
Example:
// this matches only 13 or 123
const createStateMachine = () => {
const machine = {
"": {
1: "1",
},
1: {
2: "2",
3: "3",
},
2: {
3: "3",
},
};
let state = "";
return (value) => {
const nextState = machine[state][value];
if (nextState) {
state = nextState;
return true;
}
return false;
};
};
const exec = createStateMachine();
document.querySelector("input").addEventListener("keydown", (event) => {
if (!exec(event.key)) {
event.preventDefault();
}
});
This input allows only 13 and 123
<input>
And here is the regex version but it obviously doesn't work:
const regex = /^12?3$/
document.querySelector("input").addEventListener("keydown", (event) => {
if (!regex.exec(event.key)) {
event.preventDefault();
}
});
<input>
It is possible to use the built-in regex object for that?