【问题标题】:Add formatting spaces to number input using regex and jquery ignoring existing spaces使用 regex 和 jquery 将格式化空格添加到数字输入中,忽略现有空格
【发布时间】:2020-05-19 23:54:53
【问题描述】:

我正在尝试格式化必须接受空格的模糊电话号码输入(例如<input type="text")。我希望数字格式为##### ### ###,但字符串可以包含任意顺序的数字和空格,并且在末尾和开头都有空格。任何超过 11 个数字都应添加到字符串末尾,并带有一个尾随空格。例如##### ### ### ###########...

任何帮助将不胜感激。谢谢

12345678910 => 12345 678 910
    12345678910    => 12345 678 910
  1 2 3 4 5 6 7 8 9 1 0  => 12345 678 910
12345678910111213 => 12345 678 910 111213

我试过了,但如果字符串中有空格,它就不起作用:

$('#myInput').on('blur', function () {
    $(this).val($(this).val().trim().replace(/(\s+)(\d{5})(\d{3})(\d{3})/, '$2 $3 $4'));
});

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    你想要这样的东西吗?:

    function formatNumber(str) {
        document.getElementById("myInput").value = str.replace(/ /g, "").replace(/^(\d{5})(\d{3})(\d{3})(\d*)$/, "$1 $2 $3 $4");
    }
    <form>
    <div>Simply click in this input field, change the number if you want, then click outside.</div>
    <input onblur="formatNumber(this.value)" id="myInput" name="phone" value="1 23 45 67890123456" />
    </form>

    【讨论】:

    • 不错的一个。谢谢埃里克
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-06
    • 1970-01-01
    • 1970-01-01
    • 2012-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多