【问题标题】:Add blank spaces in a string after some random digits [closed]在一些随机数字后在字符串中添加空格[关闭]
【发布时间】:2019-07-05 00:33:07
【问题描述】:

我试图在用户键入时为我的输入值添加空格,它适用于恒定数字,例如 4 个字母或 5 个字母之后。但我无法设法在某些数字之后动态添加空格。

例如

如果用户输入 1234567890

块:[3,3,4]

预期输出:123 456 7890


如果用户输入 1234567890

块:[3,2,2,3]

预期输出为:123 45 67 890

【问题讨论】:

  • 你试过什么?
  • 仅供参考:由于删除/退格和光标定位,更改用户类型的文本总是很困难。
  • @GeorgeBailey 之前我使用nosir.github.io/cleave.js 来实现这一点,它在 Vue 中使用指令,但我没有找到一种方法在用户输入时将块动态传递给 cleave.js
  • @epascarello 它不会阻止希望我的卡信息这样做的网站。而且,如果我除了继续打字之外做任何其他事情,通常会导致彻底的灾难。所以,如果我犯了一个错误并试图纠正它,它就会变得丑陋。

标签: javascript jquery arrays string


【解决方案1】:

根据用户类型处理输入可能很棘手。

虽然不完美,但一种解决方案是计算预期结果应该是什么,然后与当前的结果进行比较。如果它们不同,则使用计算出的输入更新实际输入。

下面是一个简单的例子,它甚至可以处理用户粘贴的数字。 下面的一个问题是光标位置,如果说您在中间插入了数字,但这可以通过记住光标位置并恢复来处理。

const splits = [3,3,4];
$('#a').on("input", function(){
  let count = 0;
  const breaks = splits.map(m => { const ret = m + count; count += m; return ret; });
  const a = this.value.split("").filter(f => f !== ' ');
  const s = a.map((m, ix) => {
    if (breaks.includes(ix + 1)) return m + " "
    else return m;
  }).join("");
  if (this.value.trim() !== s.trim()) this.value = s;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="a"/>

【讨论】:

    【解决方案2】:

    试试下面的代码

    function splitValue(value, index) {
        return value.substring(0, index) + " " + value.substring(index);
    }
    var test=[3,3,4];
    var secondVar = '';
    var firstVar = '1234567890';
    for(let i = 0; i < test.length; i++){
      var TestVar = splitValue(firstVar, test[i]);
      secondVar = secondVar + " " + TestVar.split(" ")[0];
      secondVar=secondVar.trim();
      if(i == 0)
    	firstVar = firstVar.replace(secondVar.trim(),'');
      else
      firstVar = firstVar.replace(secondVar.split(' ')[i + 1],'');
    }
    console.log(secondVar);

    【讨论】:

      猜你喜欢
      • 2013-10-19
      • 1970-01-01
      • 2022-11-12
      • 2018-02-04
      • 2012-04-16
      • 2016-02-13
      • 2022-01-21
      • 2014-04-17
      • 1970-01-01
      相关资源
      最近更新 更多