HTML输入框满了需要从头开始取字符

HTML input field need to take characters from beginning when full

我需要一个文本框,当达到最大长度时,需要将光标定位到开头,并且在按键输入时需要在按下按键时替换字符。我的示例代码如下。当达到最大长度时,我可以将光标移至文本框的开头,但不会替换字符。请分享有关如何更改默认输入字段行为的任何想法。

https://jsfiddle.net/yd62jugk/7/

function myFunction() {  
  if (document.getElementById("demo").selectionStart === 
      parseInt(document.getElementById("demo").getAttribute('maxlength'), 10)) {
      document.getElementById("demo").setSelectionRange(0,0);  
  }
}
<p>Press keys.</p>
<input type="text" id="demo" maxlength=5 onkeyup="myFunction()">

const input = document.querySelector('input');
const maxLength = Number(input.getAttribute('maxlength'));

input.addEventListener('keydown',(e)=>{
  let value=input.value;
  let start=input.selectionStart;
  value[start+1]=e.keyCode; 

  input.setSelectionRange(start,start+1);
  input.value=value;
  if (start===maxLength){
    input.setSelectionRange(0,1);
  }
});
console.log(maxLength);
<!DOCTYPE html>
<html>
<body>
<p>Press a key inside the text field to set a red background color.</p>

<input type="text" id="demo" maxlength="5">

</body>
</html>


const demo = document.getElementById("demo")

demo.addEventListener("keyup", myFunction )
let cursor_position = 1
let can_update = false

function myFunction(e) { 
  let max = parseInt(demo.getAttribute('maxlength'), 10)
  if ( can_update ) {
    e.target.value = replaceAt(e.target.value, cursor_position - 1, e.key)
    demo.setSelectionRange(cursor_position, cursor_position);
    (cursor_position < max ) ? cursor_position++ : cursor_position = 1
  } else if (demo.value.length === max) { can_update = true }
}

const replaceAt = (str, index, replacement) => str.substr(0, index) + replacement + str.substr(index + replacement.length)