如何用jQuery格式化电话号码

时间:2023-01-14 14:23:58

I'm currently displaying phone numbers like 2124771000. However, I need the number to be formatted in a more human-readable form, for example: 212-477-1000. Here's my current HTML:

我现在显示的电话号码是2124771000。但是,我需要将数字格式化为更易于阅读的格式,例如:212-477-1000。这是我目前的HTML:

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

9 个解决方案

#1


195  

Simple: http://jsfiddle.net/Xxk3F/3/

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

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

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

或: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');
});

Note: The .text() method cannot be used on input elements. For input field text, use the .val() method.

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

#2


49  

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

#3


11  

Don't forget to ensure you are working with purely integers.

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

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

#4


4  

Use a library to handle phone number. Libphonenumber by Google is your best bet.

使用图书馆来处理电话号码。谷歌的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

I recommend to use this package by seegno.

我建议使用seegno的这个包。

#5


3  

try something like this..

试着这样. .

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

#6


3  

Here's a combination of some of these answers. This can be used for input fields. Deals with phone numbers that are 7 and 10 digits long.

以下是其中一些答案的组合。这可以用于输入字段。处理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)
  });
}

Live example: JSFiddle

生活例子:JSFiddle

I know this doesn't directly answer the question, but when I was looking up answers this was one of the first pages I found. So this answer is for anyone searching for something similar to what I was searching for.

我知道这并不能直接回答问题,但当我查找答案时,这是我发现的第一页。这个答案适用于任何搜索类似于我搜索的东西的人。

#7


1  

I have provided jsfiddle link for you to format US phone numbers as (XXX) XXX-XXX

我为您提供了jsfiddle链接,您可以将我们的电话号码格式化为xxxx -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('');
  }
});

Live example: JSFiddle

生活例子:JSFiddle

#8


1  

Consider libphonenumber-js (https://github.com/halt-hammerzeit/libphonenumber-js) which is a smaller version of the full and famous libphonenumber.

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

Quick and dirty example:

快速和肮脏的例子:

$(".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);
}
});

(If you do use a regex to avoid a library download, avoid reformat on backspace/delete will make it easier to correct typos.)

(如果您确实使用regex来避免库下载,那么避免在backspace/delete上重新格式化将更容易纠正拼写错误。)

#9


-2  

may be this will help

这会有帮助吗

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('');

you will get +91-123-456-7890

你会得到+ 1 - 91-123-456-7890

#1


195  

Simple: http://jsfiddle.net/Xxk3F/3/

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

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

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

或: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');
});

Note: The .text() method cannot be used on input elements. For input field text, use the .val() method.

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

#2


49  

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

#3


11  

Don't forget to ensure you are working with purely integers.

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

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

#4


4  

Use a library to handle phone number. Libphonenumber by Google is your best bet.

使用图书馆来处理电话号码。谷歌的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

I recommend to use this package by seegno.

我建议使用seegno的这个包。

#5


3  

try something like this..

试着这样. .

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

#6


3  

Here's a combination of some of these answers. This can be used for input fields. Deals with phone numbers that are 7 and 10 digits long.

以下是其中一些答案的组合。这可以用于输入字段。处理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)
  });
}

Live example: JSFiddle

生活例子:JSFiddle

I know this doesn't directly answer the question, but when I was looking up answers this was one of the first pages I found. So this answer is for anyone searching for something similar to what I was searching for.

我知道这并不能直接回答问题,但当我查找答案时,这是我发现的第一页。这个答案适用于任何搜索类似于我搜索的东西的人。

#7


1  

I have provided jsfiddle link for you to format US phone numbers as (XXX) XXX-XXX

我为您提供了jsfiddle链接,您可以将我们的电话号码格式化为xxxx -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('');
  }
});

Live example: JSFiddle

生活例子:JSFiddle

#8


1  

Consider libphonenumber-js (https://github.com/halt-hammerzeit/libphonenumber-js) which is a smaller version of the full and famous libphonenumber.

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

Quick and dirty example:

快速和肮脏的例子:

$(".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);
}
});

(If you do use a regex to avoid a library download, avoid reformat on backspace/delete will make it easier to correct typos.)

(如果您确实使用regex来避免库下载,那么避免在backspace/delete上重新格式化将更容易纠正拼写错误。)

#9


-2  

may be this will help

这会有帮助吗

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('');

you will get +91-123-456-7890

你会得到+ 1 - 91-123-456-7890