如何为IBAN注册每4个字符插入空格?

Jac*_*yto 29 javascript regex

我是JavaScript的新手,我想添加到我的输入文本,IBAN帐户注册的空间插入.

<input type="text" name="iban" onkeyup="if(this.value.length > 34){this.value=this.value.substr(0, 34);}" />
Run Code Online (Sandbox Code Playgroud)

有我的输入字段; 谁能告诉我怎么做到这一点?

Jos*_*ier 59

现有答案相对较长,看起来像是过度杀戮.另外,它们不能完全工作(例如,一个问题是您无法编辑以前的字符).

对于那些感兴趣的人,根据维基百科:

允许的IBAN字符是数字0到9和26个大写拉丁字母字符A到Z.

这是一个相对较短的版本,与现有答案类似:

document.getElementById('iban').addEventListener('input', function (e) {
  e.target.value = e.target.value.replace(/[^\dA-Z]/g, '').replace(/(.{4})/g, '$1 ').trim();
});
Run Code Online (Sandbox Code Playgroud)
<label for="iban">iban</label>
<input id="iban" type="text" name="iban" />
Run Code Online (Sandbox Code Playgroud)


如上所述,需要注意的是,您无法返回并编辑以前的字符.如果要解决此问题,则需要通过最初访问selectionEnd属性然后在应用正则表达式格式设置设置插入符的位置来检索插入符的当前位置.

document.getElementById('iban').addEventListener('input', function (e) {
  var target = e.target, position = target.selectionEnd, length = target.value.length;
  
  target.value = target.value.replace(/[^\dA-Z]/g, '').replace(/(.{4})/g, '$1 ').trim();
  target.selectionEnd = position += ((target.value.charAt(position - 1) === ' ' && target.value.charAt(length - 1) === ' ' && length !== target.value.length) ? 1 : 0);
});
Run Code Online (Sandbox Code Playgroud)
<label for="iban">iban</label>
<input id="iban" type="text" name="iban" />
Run Code Online (Sandbox Code Playgroud)

当插入符号后的字符是空格时,您会注意到存在一个小问题(因为在最初检索插入符号的位置时没有考虑空间).要解决此问题,如果后续字符是空格(假设实际添加了空格 - 通过比较替换字符之前和之后的长度来确定),则手动增加位置.

  • 适合我:)稍微改进:如果用户输入小写的国家代码,则不会发生任何输入.`e.target.value`之后的`.toUpperCase()`修复了这个问题. (2认同)

Dav*_*mas 13

使用纯JavaScript,我建议:

function space(el, after) {
    // defaults to a space after 4 characters:
    after = after || 4;

    /* removes all characters in the value that aren't a number,
       or in the range from A to Z (uppercase): */
    var v = el.value.replace(/[^\dA-Z]/g, ''),
    /* creating the regular expression, to allow for the 'after' variable
       to be used/changed: */
        reg = new RegExp(".{" + after + "}","g")
    el.value = v.replace(reg, function (a, b, c) {
        return a + ' ';
    });
}

var el = document.getElementById('iban');
el.addEventListener('keyup', function () {
    space(this, 4);
});
Run Code Online (Sandbox Code Playgroud)

JS小提琴演示.

有点姗姗来迟,我重写上面来处理字符串,而不是DOM节点:

function space(str, after) {
    if (!str) {
        return false;
    }
    after = after || 4;
    var v = str.replace(/[^\dA-Z]/g, ''),
        reg = new RegExp(".{" + after + "}", "g");
    return v.replace(reg, function (a) {
        return a + ' ';
    });
}

var el = document.getElementById('iban');
el.addEventListener('keyup', function () {
    this.value = space(this.value, 4);
});
Run Code Online (Sandbox Code Playgroud)

JS小提琴演示.

参考文献: