最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Formatting the phone number - Stack Overflow

programmeradmin5浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 11

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

发布评论

评论列表(0)

  1. 暂无评论