当用户在输入字段中键入值时,使用 javascript 格式化输入值

Formatting input value using javascript as the user types a value into the input field

我有一个长度为 14 的输入字段,用户可以在其中键入一个值。当用户输入时,我希望在前 2 个字符之后自动添加 space,然后在接下来的 3 个字符之后,然后在接下来的 3 个字符之后自动添加。所以如果用户要输入12345678901,应该格式化为12 345 678 901.

另外,当用户使用 backspace 清除字符时,space 应该自动删除。所以在上面的例子中,当光标到达 9 并且用户回击 space 时,光标应该向左移动两个位置以清除 9 和它之前的 space。

我尝试按照此处的信用卡格式设置 ,但无法理解它是如何完成的。上面 link 的代码是

formatInput(event: any) {
    var v = event.value.replace(/\s+/g, '').replace(/[^0-9]/gi, '')
    var matches = v.match(/\d{4,16}/g);
    var match = matches && matches[0] || ''
    var parts = []

    for (let i=0, len=match.length; i<len; i+=4) {
       parts.push(match.substring(i, i+4))
    }

    if (parts.length) {
      (<HTMLInputElement>document.getElementById("txtInput")).value = 
        parts.join(' ')
    } else {
        (<HTMLInputElement>document.getElementById("txtInput")).value 
          = event.value;
    }
}

以上代码每 4 位数字后生成 spaces。我的要求是接受任何字符并在前 2 个字符之后生成 spaces,然后在接下来的 3 个字符之后生成,然后在接下来的 3 个字符之后生成。请帮我解决这个问题。

这是一个可以解决您的问题的工作示例。

function format(str) {
 if (str.length < 2) return str
  else {
    let [fl,sl,...lstr] = str
    lstr =lstr.reduce((acc, el, i) => (i % 3 ? acc[acc.length - 1]+=el : acc.push(el), acc),[])
  return `${fl}${sl} ${lstr.join(' ')}`.trim()
  }
}



const [input,result]= document.querySelectorAll('#input,#result')
input.oninput =()=>{
    const i = input.value.replace(/\s/g, '');
    input.value= format(i)
  }
<input type=text id=input />
<p id="result"></p>