Use jQuery to insert hyphen into phone # in td fields

I have a table with a bunch of phone numbers requested from a database. I want to insert hyphens in the phone number, and instead of: "0000000000" the user will see: "000-000-0000". Not very good at regex, but this is what I have tried so far:

  $('.views-field-phone').each(function(){
      $(this).insertAfter(/(.{3})/g,"-1-")
      $(this).insertAfter(/(.{7})/g,"-1-")
  });
+3
source share
3 answers

may not be 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)) 
});
+6
source

Here is a simple function that I use to format phone numbers, nothing special but to complete the task.

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

Conclusion:

<h1>(123) 456-7890</h1>
<h1>1 (123) 456-7890</h1>
<h1>undefined</h1>

Jsfiddle example .

+2
source

Why can't you use javascript substr()? If the numbers are even, you can break them down like this: 3-3-4 characters.

0
source

Source: https://habr.com/ru/post/1795785/


All Articles