2012-01-06 75 views
81

我正在顯示電話號碼,例如2124771000。但是,我需要以更易讀的格式對數字進行格式化,例如:212-477-1000。這是我目前的HTML如何用jQuery格式化電話號碼

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

太晚答案,但只是爲了幫助那些登陸此頁面的人 網址:http://igorescobar.github.io/jQuery-Mask-Plugin/ – Senthil 2013-10-08 17:17:24

+5

不知道我是否理解這個關閉狀態。不建設性似乎不正確...我發現這些信息非常有用,並且直接關係到這裏帶來的問題。我不反對它被關閉的事實,但顯示被關閉的原因 – 2014-07-10 16:53:16

+0

也許這個問題被編輯過,並且在......之前描述性較差,它似乎是一個完全有效的SO問題和答案,還有很多upvotes。 – 2015-12-29 16:47:17

回答

190

簡單: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'); 
}); 
+3

我修改了這個以支持輸入字段中的「更改」事件。 http://jsfiddle.net/gUsUK/ – 2013-05-29 18:48:26

+2

正則表達式更健壯一些(雖然它需要一個自定義替換函數)會是/(\ d {3})?(\ d {3})(\ d { 4})$ /'如果沒有地區代碼 – RevanProdigalKnight 2015-08-21 19:21:57

+0

它對全世界的電話號碼有效嗎? – user2601010 2016-07-27 02:54:50

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

@AndreasAL中起作用:因爲正則表達式引擎的開銷很大,特別是對於輸入格式已知的情況,簡單字符串操作的FAR效率更高。當然,使用正則表達式解決問題的規則只會讓你有兩個問題。 – 2012-01-06 16:26:48

+4

該解決方案還適當地格式化帶有字母的電話號碼,如「212555IDEA」。 – 2013-01-09 20:12:40

+0

這在Windows環境中運行良好,但不適用於iOS設備。有沒有其他的選擇,在平臺 – 2017-07-01 16:20:49

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

不要忘記確保您使用純粹的整數。

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

非常好的一點,值得注意的作品。 – 2013-02-15 22:39:30

3

下面是這些答案的組合。這可以用於輸入字段。處理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

我知道這並不直接回答這個問題,但是當我在查找答案,這是我發現的第一個頁面。所以這個答案適用於任何尋找類似於我正在尋找的東西的人。

1

我提供的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

4

使用庫來處理電話號碼。谷歌的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的package

-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

0

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

(如果你使用正則表達式來避免庫下載,避免退格格式化/刪除將使它更容易糾正錯別字。)