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

调用正则表达式后,游标将结束.所以我尝试了修复,但也无法正常工作.怎么能修好?我的目标:如果字段为空并且输入数字>光标在结束时,如果返回添加或删除任何数字>光标在适当的位置(不是在末尾)

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

最佳答案 将选择范围设置为您创建的“位置”,如果包含“ – ”,则增加位置,如下所示:

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);
});
点赞