简体   繁体   English

使用 javascript 格式化输入值作为用户在输入字段中键入值

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

I have an input field of length 14 into which the user types a value.我有一个长度为 14 的输入字段,用户在其中输入一个值。 As the user types into it, I would like a space to be added automatically after first 2 characters and then after next 3 characters and then after next 3 characters.当用户输入它时,我希望在前 2 个字符之后自动添加一个空格,然后在接下来的 3 个字符之后,然后在接下来的 3 个字符之后。 so if the user wants to enter 12345678901 , it should be formatted to 12 345 678 901 .所以如果用户想输入12345678901 ,它应该被格式化为12 345 678 901

Also when user uses backspace to clear the characters, the space should automatically be removed.此外,当用户使用退格键清除字符时,应自动删除空格。 So in the above case when the cursor reaches 9 and user hits backspace, the cursor should move two places to left clearing 9 and the space before it.因此,在上述情况下,当 cursor 达到 9 并且用户按退格键时,cursor 应该向左移动两个位置,清除 9 和它之前的空间。

I tried following the credit card formatting here Format credit card number but couldn't understnd how it is done.我尝试按照此处的信用卡格式格式化信用卡号,但无法理解它是如何完成的。 The code from above link is上面链接的代码是

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;
    }
}

The above code generates spaces after every 4 digits.上面的代码在每 4 位之后生成一个空格。 My requirement is to accept any characters and generate spaces after first 2 characters and then after next 3 characters and then after next 3 characters.我的要求是接受任何字符并在前 2 个字符之后生成空格,然后在接下来的 3 个字符之后,然后在接下来的 3 个字符之后生成空格。 Please help me out with this.这个你能帮我吗。

this is a working example that solves your problem.这是一个可以解决您的问题的工作示例。

 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM