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 ing in the form of 0123456789 from the database and output should be (012)345-6789.
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 ing in the form of 0123456789 from the database and output should be (012)345-6789.
Share Improve this question asked Apr 2, 2012 at 9:30 NitishNitish 8564 gold badges16 silver badges27 bronze badges 5- What is the server-side language? It'd be much easier to format the number server-side. – JJJ Commented Apr 2, 2012 at 9:32
- I am using struts2 framwork and java language. – Nitish Commented Apr 2, 2012 at 9:33
- for formatting strings in javascript: stackoverflow./questions/1038746/… – mshsayem Commented Apr 2, 2012 at 9:37
- Are the numbers in the DB all in the same format? Or do you have numbers like +41792359866 or 0041792359866 or +41-792-349-866 (i.e. japanese format vs nanp) – PhilW Commented Apr 2, 2012 at 9:52
- they all are in the format of 0123456789 – Nitish Commented Apr 2, 2012 at 10:06
3 Answers
Reset to default 11I 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/en/JavaScript/Reference/Global_Objects/String/replace
phone = "0123456789"
formated_phone = "("+phone.substring(0,3)+")"+phone.substring(3,6)+"-"+phone.substring(6,11)
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"));