将输入光标设置为javascript正则表达式之后的正确位置

Set input cursor to proper position after javascript regex

本文关键字:之后 位置 正则表达式 javascript 输入 光标 设置      更新时间:2023-09-26

调用regex后,光标将结束。所以我尝试了这个修复,但也没有正常工作。这怎么能解决?我的目标:如果字段为空并且键入数字>光标在末尾,如果返回添加或删除任何数字>光标位于正确位置(不在末尾)

document.getElementById('target').addEventListener('input', function (e) {
  var target = e.target,
      position = target.selectionStart; // Capture initial position
  target.value = target.value.replace(/'B(?=('d{3})+(?!'d))/g, "-");// This triggers the cursor to move.
  target.selectionEnd = position;    // Set the cursor back to the initial position.
});

Fiddle

将选择范围设置为您创建的"position",如果包含"-",则会增加位置,如下所示:

document.getElementById('target').addEventListener('input', function (e) {
  var target = e.target,
  position = target.selectionStart; // Capture initial position
  var old = target.value;
  target.value = target.value.replace(/'B(?=('d{3})+(?!'d))/g, "-");
  if(old != target.value)
    position++;
  target.setSelectionRange(position, position);
});

尝试setSelectionRange()

你的小提琴:**http://jsfiddle.net/ku8bg0c9/2/

我把10000作为长度,因为我认为永远不会输入10000个字符。但您可以根据输入字符串的长度设置长度。

document.getElementById('target').addEventListener('input', function (e) {
    var target = e.target,
        position = target.selectionStart; // Capture initial position
    target.value = target.value.replace(/'B(?=('d{3})+(?!'d))/g, "-"); // This triggers the cursor to move.
    target.selectionEnd = position; // Set the cursor back to the initial position.
    target.setSelectionRange(10000, 10000);
});