格式化电话号码以匹配特定模式?

时间:2015-08-06 09:52:47

标签: javascript jquery regex

我想知道是否有一种很好的方法可以根据设置的字符串模式格式化数字,我想使用不同的电话号码,例如0123456789,输出为012-345-6789001123456789得到的输出为00-11-234-567等。我在考虑将模式作为数据属性放在输入上,如data-format="xxx-xxx-xxxx""xx-xx-xxx-xxx",具体取决于所选内容然后尝试将输入数字与这种模式,但完全确定如何实现这一点,或者它是否是正确的方法?此格式不需要反映在输入中,格式将用于在摘要中显示数字。

示例代码:

<form action="" class="js-form">
    <label>Telephone Number</label>
    <input type="number" class="js-phone" data-format="xx-xx-xxx-xxx">
    <input type="submit" class="js-submit">
</form>

function formatTelephone(number, format) {
    // split number
    // loop number
    // pop each character
    // .replace pattern
}

$formAction.on('click', function(event) {
    event.preventDefault();

    var telephoneNumber = $phoneInput.val(),
        telephoneFormat = $phoneInput.data('format');

    formatTelephone(telephoneNumber, telephoneFormat);
});

我是否应该拆分数字,循环遍历每个字符并更换相应的模式字符,同时以某种方式避免破折号?

2 个答案:

答案 0 :(得分:0)

  • 从第一个

  • 中删除所有非数字字符
  • 循环遍历格式中的所有字符,如果char =&#39; x&#39;然后将剥离数字中的相应数字放到该位置,如果不是 - 从结果字符串中的格式中保留字符。

您应该跟踪数字中的位置,并在放入数字时将其递增。首先,您应该通过计算x来验证格式本身。

答案 1 :(得分:0)

这是我刚创建的一个例子,它有效。

有必要将input type更改为text,否则它将不接受-,因为它只接受数字。

<form action="" class="js-form">
    <label>Telephone Number</label>
    <input type="text" class="js-phone" data-format="xxx-xxx-xxxx"/>
    <input type="submit" class="js-submit"/>
</form>

我评论了JS:

$('.js-form').on('submit', function(event) {
    event.preventDefault();
    // I'm passing the object and not the value so I'll be able to update its value
    // at the end of the function execution
    var telephoneNumber = $('.js-phone'),
        telephoneFormat = $('.js-phone').data('format');

    formatTelephone(telephoneNumber, telephoneFormat);
});

function formatTelephone(number, format) {
    // Considering that - will always be the separator
    patternList = format.split('-');
    pattern = ""
    // Creates the regex as a string
    // The \\ in the pattern was required to escape the \, which is required in this case
    patternList.forEach(function(x) {
        pattern += "(\\d{0,"+x.length+"})";
    });
    // Create the RegExp
    var regex = new RegExp(pattern);
    // Try to match it with the number passed in the parameter
    var result = number.val().match(regex);
    // Will store the formatted number
    formatted = "";
    // Loop through the patterList to add the - back
    for(x=1;x<=patternList.length; x++) {
        formatted += (result[x] + (x==patternList.length ? '' : '-'));
    }
    // Now you can do whatever you need with the formatted variable
    number.val(formatted);
}

JSFiddle

相关问题