What I want is NOT to emulate a key press event in javascript, but get the value of a string after a key press.
To clarify; given a text input, I want to see what the value of my text input would be if the user pressed a certain key.
i.e, I want the following function.
function getStringValueAfterKeyPress(string, cursorPosition, keyCode) {
// returns string value after key press with provided code on provided cursor position
}
getStringValueAfterKeyPress('test', 4, 8) // returns 'tes' (8 is keycode of backspace)
getStringValueAfterKeyPress('test', 4, 37) // returns 'test' (37 is keycode of left arrow, hence string value has not changed)
getStringValueAfterKeyPress('test', 4, 49) // returns 'test1' (49 is keycode of '1')
And so on. Is there a simple way of doing this?
P.S my use case will be to use this method on an afterKeyDown event, get the value of my input element after this key press using this method, and if it does not match a certain regex prevent the action.