正在格式化电话号码

Formatting the phone number

本文关键字:电话号码 格式化      更新时间:2023-09-26

下面的文本框在从数据库中获取电话号码后打印该号码的值。

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

如何以(xxx)xxx-xxxx格式打印此值。注:这些值以0123456789的形式来自数据库输出应为(012)345-6789。

我更喜欢使用replaceregexp(代码更少,功能更多)。

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

参考:https://developer.mozilla.org/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"));