如何改变输入值同时避免光标移到末尾?

英文版请见

https://stackoverflow.com/questions/76269117/how-to-change-the-value-of-input-without-the-position-of-cursor-going-to-the-end

如果可以请查看英文版,其中两个回答都有些问题,可以参考。查看英文版可以运行代码段。

我有一个输入框,然后想将输入的字母五个五个分开来,但是如果我不在末尾输入或者删除的话,光标就会自动跳到末尾。
比如现在输入框里有ABCDE FGHJK;如果我删除开头的A的话,那么光标会自动跳到末尾。

let Input = document.createElement("input"); 
Input.setAttribute("type", "text");
Input.style.width = "100%";
Input.style.height = "30px";
Input.style.fontSize = "20px";

// The code AFTER this need modification and improvement

Input.addEventListener("input", function(e) {
      Input.value = Input.value.replace(/\s*/g,"");
      Input.value = Input.value.replace(/(.{5})/g, '$1 ');
      Input.value = Input.value.trim();
});

// The code BEFORE this need modification and improvement

document.body.appendChild(Input);

如何修改代码阻止光标移到末尾,请不要使用原生js以外的如css html jquery等。
代码尽量简洁谢谢!

参考GPT和自己的思路:要防止光标移动到输入框末尾,可以在修改输入框的值前先保存光标的位置,修改完值后再将光标位置还原。下面的代码演示了如何实现该功能:

let Input = document.createElement("input"); 
Input.setAttribute("type", "text");
Input.style.width = "100%";
Input.style.height = "30px";
Input.style.fontSize = "20px";
Input.addEventListener("input", function(e) {
  // 保存光标位置
  let start = Input.selectionStart; 
  let end = Input.selectionEnd;

  // 修改输入框的值
  Input.value = Input.value.replace(/\s\*/g,"");
  Input.value = Input.value.replace(/(.{5})/g, '$1 ');
  Input.value = Input.value.trim();

  // 还原光标位置
  Input.setSelectionRange(start, end); 
});
document.body.appendChild(Input);

在输入时,如果光标不在输入框末尾,用户的输入会在当前光标位置插入,这样可以避免光标移动。