Javascript 如何使用 jQuery 格式化电话号码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8760070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to format a phone number with jQuery
提问by Xtian
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>
回答by andlrc
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})/, '--');
});
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)/, '--');
});
Note: The .text() method cannot be used on input elements. For input field text, use the .val() method.
注意: .text() 方法不能用于输入元素。对于输入字段文本,请使用 .val() 方法。
回答by Marc B
var phone = '2124771000',
formatted = phone.substr(0, 3) + '-' + phone.substr(3, 3) + '-' + phone.substr(6,4)
回答by Trenton Bost
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})/, '' + separator + '' + separator + '' );
return DATA;
});
回答by Cruz Nunez
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})/, "-");
} else if (number.length == 10) {
number = number.replace(/(\d{3})(\d{3})(\d{4})/, "() -");
}
$(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.
我知道这并不能直接回答问题,但是当我查找答案时,这是我找到的第一页。所以这个答案适用于任何正在寻找类似于我正在寻找的东西的人。
回答by aloisdg moving to codidact.com
Use a library to handle phone number. Libphonenumberby Google is your best bet.
使用库来处理电话号码。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
I recommend to use this packageby seegno.
我建议通过seegno使用这个包。
回答by Kapilrc
I have provided jsfiddle link for you to format US phone numbers as (XXX) XXX-XXX
我已经为您提供了 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('');
}
});
Live example: JSFiddle
现场示例:JSFiddle
回答by Anuj Patel
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
}
}
});
回答by Adam Lane
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.)
(如果您确实使用正则表达式来避免库下载,请避免在退格/删除时重新格式化将更容易更正拼写错误。)
回答by Penny Liu
An alternative solution:
另一种解决方案:
function numberWithSpaces(value, pattern) {
var i = 0,
phone = value.toString();
return pattern.replace(/#/g, _ => phone[i++]);
}
console.log(numberWithSpaces('2124771000', '###-###-####'));
回答by Tod Birdsall
I found this question while googling for a way to auto-format phone numbers via a jQuery plugin. The accepted answer was not ideal for my needs and a lot has happened in the 6 years since it was originally posted. I eventually found the solution and am documenting it here for posterity.
我在谷歌搜索通过 jQuery 插件自动格式化电话号码的方法时发现了这个问题。接受的答案并不适合我的需求,自最初发布以来的 6 年里发生了很多事情。我最终找到了解决方案,并在此处记录下来以供后代使用。
Problem
问题
I would like my phone number html input field to auto-format (mask) the value as the user types.
我希望我的电话号码 html 输入字段在用户键入时自动格式化(屏蔽)该值。
Solution
解决方案
Check out Cleave.js. It is a very powerful/flexible and easy way to solve this problem, and many other data masking issues.
查看Cleave.js。这是解决此问题以及许多其他数据屏蔽问题的非常强大/灵活且简单的方法。
Formatting a phone number is as easy as:
格式化电话号码非常简单:
var cleave = new Cleave('.input-element', {
phone: true,
phoneRegionCode: 'US'
});