I have a table with a bunch of phone numbers queried fro开发者_如何转开发m a database. I want to insert hyphens into the phone number so instead of: "0000000000" the user will see: "000-000-0000". Not very good at regex but this is what I've tried so far:
$('.views-field-phone').each(function(){
$(this).insertAfter(/(.{3})/g,"-1-")
$(this).insertAfter(/(.{7})/g,"-1-")
});
maybe not optimal but...
string = string.substring(0,3) + '-' + string.substring(3,6) + '-' + string.substring(6,10);
or for your case...
$('.views-field-phone').each(function(){
var string = $(this).html();
$(this).html(string.substring(0,3) + '-' + string.substring(3,6) + '-' + string.substring(6,10))
});
Here is a simple function that I use to format phone numbers, nothing special but gets the job done.
function formatPhoneNumber(phoneNumber) {
var rawPhoneNumber = phoneNumber.replace("(", "").replace(")", "").replace(/-/g, "").replace(/ /g, "");
if (isNaN(rawPhoneNumber)) {
return null;
}
if (rawPhoneNumber.length == 10) {
return "(" + rawPhoneNumber.substring(0, 3) + ") " + rawPhoneNumber.substring(3, 6) + "-" + rawPhoneNumber.substring(6, 10);
}
if (rawPhoneNumber.length == 11) {
return rawPhoneNumber.substring(0, 1) + " (" + rawPhoneNumber.substring(1, 4) + ") " + rawPhoneNumber.substring(4, 7) + "-" + rawPhoneNumber.substring(7, 11);
}
}
Test Cases:
$("body").append("<h1>" + formatPhoneNumber("1234567890") + "</h1>");
$("body").append("<h1>" + formatPhoneNumber("11234567890") + "</h1>");
$("body").append("<h1>" + formatPhoneNumber("11267890") + "</h1>");
Will Output:
<h1>(123) 456-7890</h1>
<h1>1 (123) 456-7890</h1>
<h1>undefined</h1>
Example on jsfiddle.
Why can't you just use the javascript substr()
? If the numbers are uniform, you can split it like this: 3-3-4 chars.
精彩评论