触发替换中的正则表达式时光标向后移动,JavaScript

cursor go backward when triggered the regex in the replace, JavaScript

我已将 link 附加到 fiddle 以模拟我遇到的问题。

例如: 我输入了 12345 > 将光标指向中间 12|345 > 输入 "space" > 123|45

输入"space"后光标会后退。

问题:如何让它保持原样?

Here is the link to fiddle

document.querySelector("#removeSpace").onkeyup =  function()
{

    var start = this.selectionStart,
        end = this.selectionEnd;

    this.value = this.value.replace(/\s/g,"");
    this.setSelectionRange(start, end);
};

您需要检查空格是否被匹配,并设置偏移量等于匹配长度的选择。但是,为了避免空格输入,您可以使用 input 事件:

$(function(){
  $('#removeSpace').bind('input', function(){
      var start = this.selectionStart,
            end = this.selectionEnd;
      var offset=0;
      this.value = this.value.replace(/\s+/g, function([=10=]) {offset=[=10=].length; return "";});
      if (offset > 0)
        this.setSelectionRange(start-offset, end-offset);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="removeSpace" type="Text" />

replace(/\s+/g, function([=15=]) {offset=[=15=].length; return "";}) 部分匹配 1 个或多个空格并通过 [=16=] 变量将它们传递给回调。它的长度被分配给 offset 变量,并从当前开始和结束光标位置中减去。 return "" 删除匹配项,找到所有空格。

可以应用相同的逻辑来修复您的解决方案,使用 keyup:

document.querySelector("#removeSpace").onkeyup =  function()
{
    
    var start = this.selectionStart,
        end = this.selectionEnd;
    var offset=0;
    this.value = this.value.replace(/\s+/g, function([=12=]) {offset=[=12=].length; return "";});
    if (offset > 0)
     this.setSelectionRange(start-offset, end-offset);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="removeSpace" type="Text" />