6

The below textbox is printing the value of the phone number after getting it from the database.

<table>
<tr>
<td>
<s:textfield theme="simple" name="phoneNumber"/>
</td>
</tr>
</table>

How to print this value in the format (xxx) xxx-xxxx. Note: The values are coming in the form of 0123456789 from the database and output should be (012)345-6789.

Nitish
  • 834
  • 4
  • 15
  • 26

3 Answers3

10

I would prefer to use replace and regexp (less code, more features).

         var phone = "0123456789";
         phone.replace(/(\d{3})(\d{3})(\d{4})/,"($1)$2-$3"); // (012)345-6789

Reference: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace

antonjs
  • 14,060
  • 14
  • 65
  • 91
2
phone = "0123456789"
formated_phone = "("+phone.substring(0,3)+")"+phone.substring(3,6)+"-"+phone.substring(6,11)
Daniil Ryzhkov
  • 7,416
  • 2
  • 41
  • 58
0

const formatPhoneNumber = (phoneNumber) => {
  // convert the raw number to (xxx) xxx-xxx format
  const x = phoneNumber && phoneNumber.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
  return !x[2] ? x[1] : `(${x[1]}) ${x[2]}${x[3] ? `-${x[3]}` : ''}`;
};

console.log(formatPhoneNumber("1111111111"));
Sree
  • 1
  • 1