Changing user input on keypress is a definite anti-pattern! There are numerous scenarios where this approach falls short and becomes challenging to work with... When the user types quickly, when content is pasted, or if the event is triggered by a non-typing key.
A potentially better solution, in my humble opinion (IMHO)
, is to link user input with a read-only modified input (or another UI element)!
<input id="rkjv" type="text">value<br/><br/>
<input id="up" type="text">up<br/><br/>
<input id="down" type="text" readonly>down<br/><br/>
let userInput = document.getElementById('rkjv')
let prefix='@'
let suffix='%'
function adjustInput(el){
let originalVal = el.target.value;
if(originalVal!==''){
let adjustedVal = originalVal
if(!adjustedVal.match(new RegExp('^' + prefix))){
adjustedVal = prefix + adjustedVal
}
if(!adjustedVal.match(new RegExp(suffix + '$'))){
adjustedVal = adjustedVal + suffix
}
if(adjustedVal!==originalVal){
el.target.value = adjustedVal
}
}
}
userInput.onkeyup = adjustUserInput
/* :] */
function adjustOutput(el){
let userOutput = document.getElementById('down')
let originalVal = el.target.value;
let adjustedVal = originalVal
if(adjustedVal !== ''){
adjustedVal = prefix + adjustedVal + suffix
}
userOutput.value = adjustedVal
}
let userInputUp = document.getElementById('up')
userInputUp.onkeyup = adjustOutput
Take a look at how not to do it in this terrible implementation
https://jsfiddle.net/6f5zgtqo/5/