如何使用jQuery格式化电话号码


93

我目前正在显示类似的电话号码2124771000。但是,我需要将数字格式化为更易于理解的格式,例如:212-477-1000。这是我目前的情况HTML

<p class="phone">2124771000</p>

1
答案太晚了,但对寻求帮助的人来说,访问此页面URL的地址:igorescobar.github.io/jQuery-Mask-Plugin
Senthil

5
不确定我是否了解这一状态。“非建设性”似乎并不正确……我发现这些信息非常有用,并且与导致我出现问题的直接关联。我不反对关闭它的事实,但是显示关闭的原因
Brett Weber

也许这个问题在之前被编辑过并且没有那么描述性……似乎对我来说是一个非常有效的SO问答,还有很多反对意见。
凯文·尼尔森

Answers:


217

简单:http//jsfiddle.net/Xxk3F/3/

$('.phone').text(function(i, text) {
    return text.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');
});

或:http : //jsfiddle.net/Xxk3F/1/

$('.phone').text(function(i, text) {
    return text.replace(/(\d\d\d)(\d\d\d)(\d\d\d\d)/, '$1-$2-$3');
});

注意:.text()方法不能在输入元素上使用。对于输入字段文本,请使用.val()方法。


4
我已经对其进行了修改,以支持输入字段中的“更改”事件。jsfiddle.net/gUsUK
Zach Shallbetter

3
如果/(\d{3})?(\d{3})(\d{4})$/没有区号,则使用正则表达式会更健壮(尽管它需要自定义替换功能)
RevanProdigalKnight 2015年

它适用于全世界的电话号码吗?
RamPrasadBismil '16

如果页面上有多个电话号码,请考虑使用$(selector).each()函数轻松将此掩码应用于所有号码。
Daniel Siebert

我想用按键和模糊事件来实现它。当数字少于10时,它不会格式化电话号码。示例代码为: $('#x_phone').on('keypress blur',function() { var ph = $(this).val(); var temp = ph.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3'); $(this).val(temp); //alert(temp); });
Musaddiq Khan,

54
var phone = '2124771000',
    formatted = phone.substr(0, 3) + '-' + phone.substr(3, 3) + '-' + phone.substr(6,4)

7
@AndreasAL:因为正则表达式引擎的开销很大,尤其是对于已知输入格式且简单的字符串操作更有效的事情。当然,有一个规则,使用正则表达式解决问题只会使您遇到两个问题。
Marc B

4
此解决方案还可以正确格式化其中带有字母的电话号码,例如“ 212555IDEA”。
杰森·怀特霍恩

1
这在Windows环境中运作良好,但在iOS装置中无法运作。在这两个平台上都可以使用任何替代方法

12

不要忘记确保您使用的是纯整数。

var separator = '-';
$( ".phone" ).text( function( i, DATA ) {
    DATA
        .replace( /[^\d]/g, '' )
        .replace( /(\d{3})(\d{3})(\d{4})/, '$1' + separator + '$2' + separator + '$3' );
    return DATA;
});

8

这是其中一些答案的组合。可以用于输入字段。处理7到10位数字的电话号码。

// Used to format phone number
function phoneFormatter() {
  $('.phone').on('input', function() {
    var number = $(this).val().replace(/[^\d]/g, '')
    if (number.length == 7) {
      number = number.replace(/(\d{3})(\d{4})/, "$1-$2");
    } else if (number.length == 10) {
      number = number.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
    }
    $(this).val(number)
  });
}

现场示例:JSFiddle

我知道这并不能直接回答问题,但是当我查找答案时,这是我发现的第一页。因此,此答案适用于任何正在寻找与我正在寻找的东西相似的东西的人。


5

使用库来处理电话号码。Google的Libphonenumber是您最好的选择。

// Require `PhoneNumberFormat`.
var PNF = require('google-libphonenumber').PhoneNumberFormat;

// Get an instance of `PhoneNumberUtil`.
var phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance();

// Parse number with country code.
var phoneNumber = phoneUtil.parse('202-456-1414', 'US');

// Print number in the international format.
console.log(phoneUtil.format(phoneNumber, PNF.INTERNATIONAL));
// => +1 202-456-1414

我建议Seegno 使用此软件包


4

我已为您提供了jsfiddle链接,用于将美国电话号码格式设置为(XXX)XXX-XXX

 $('.class-name').on('keypress', function(e) {
  var key = e.charCode || e.keyCode || 0;
  var phone = $(this);
  if (phone.val().length === 0) {
    phone.val(phone.val() + '(');
  }
  // Auto-format- do not expose the mask as the user begins to type
  if (key !== 8 && key !== 9) {
    if (phone.val().length === 4) {
      phone.val(phone.val() + ')');
    }
    if (phone.val().length === 5) {
      phone.val(phone.val() + ' ');
    }
    if (phone.val().length === 9) {
      phone.val(phone.val() + '-');
    }
    if (phone.val().length >= 14) {
      phone.val(phone.val().slice(0, 13));
    }
  }

  // Allow numeric (and tab, backspace, delete) keys only
  return (key == 8 ||
    key == 9 ||
    key == 46 ||
    (key >= 48 && key <= 57) ||
    (key >= 96 && key <= 105));
})

.on('focus', function() {
  phone = $(this);

  if (phone.val().length === 0) {
    phone.val('(');
  } else {
    var val = phone.val();
    phone.val('').val(val); // Ensure cursor remains at the end
  }
})

.on('blur', function() {
  $phone = $(this);

  if ($phone.val() === '(') {
    $phone.val('');
  }
});

现场示例:JSFiddle


如何更改此模式以从左到右显示数字,例如==>(021)88888888
Mostafa

3

尝试这样的事情..

jQuery.validator.addMethod("phoneValidate", function(number, element) {
    number = number.replace(/\s+/g, ""); 
    return this.optional(element) || number.length > 9 &&
        number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");

$("#myform").validate({
  rules: {
    field: {
      required: true,
      phoneValidate: true
    }
  }
});

2

考虑libphonenumber-js(https://github.com/halt-hammerzeit/libphonenumber-js),它是完整的著名libphonenumber的较小版本。

快速而肮脏的例子:

$(".phone-format").keyup(function() {
// Don't reformat backspace/delete so correcting mistakes is easier
if (event.keyCode != 46 && event.keyCode != 8) {
    var val_old = $(this).val();
    var newString = new libphonenumber.asYouType('US').input(val_old);
    $(this).focus().val('').val(newString);
}
});

(如果您确实使用正则表达式来避免下载库,请避免在退格键/删除键上重新设置格式,这将更容易纠正错别字。)


2

替代解决方案:

function numberWithSpaces(value, pattern) {
  var i = 0,
    phone = value.toString();
  return pattern.replace(/#/g, _ => phone[i++]);
}

console.log(numberWithSpaces('2124771000', '###-###-####'));


1

我在搜寻通过jQuery插件自动格式化电话号码的方式时发现了这个问题。接受的答案对我的需求而言并不理想,自最初发布以来的6年中发生了很多事情。我最终找到了解决方案,并在此进行记录以供后代参考。

问题

我希望我的电话号码html输入字段在用户键入时自动格式化(掩码)该值。

查看Cleave.js。这是解决此问题以及许多其他数据屏蔽问题的非常强大/灵活且容易的方法。

格式化电话号码很容易:

var cleave = new Cleave('.input-element', {
    phone: true,
    phoneRegionCode: 'US'
});

1

输入:

4546644645

码:

PhoneNumber = Input.replace(/(\d\d\d)(\d\d\d)(\d\d\d\d)/, "($1)$2-$3");

输出:

(454)664-4645

0
 $(".phoneString").text(function(i, text) {
            text = text.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
            return text;
        });

输出:-( 123)657-8963


-2

也许这会有所帮助

var countryCode = +91;
var phone=1234567890;
phone=phone.split('').reverse().join('');//0987654321
var formatPhone=phone.substring(0,4)+'-';//0987-
phone=phone.replace(phone.substring(0,4),'');//654321
while(phone.length>0){
formatPhone=formatPhone+phone.substring(0,3)+'-';
phone=phone.replace(phone.substring(0,3),'');
}
formatPhone=countryCode+formatPhone.split('').reverse().join('');

您会得到+ 91-123-456-7890

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.