javascript 使用可能为空的捕获组格式化电话号码

mlnl4t2r  于 2023-03-28  发布在  Java
关注(0)|答案(2)|浏览(142)

我正在尝试在用户输入时格式化电话号码,我几乎已经得到了它,但我似乎就是不能把它带回家。
这就是我要找的:

+12345678900 --> +1 (234) 567 89-00
+1234567890  --> +1 (234) 567 89-0
+123456789   --> +1 (234) 567 89-
+12345       --> +1 (234) 5
+123         --> +1 (23

我的方法是:

'+12345678900'
    .replace(
        /^(\+\d{1})?(\d{1,3})?(\d{1,3})?(\d{1,2})?(\d{1,2})?$/,
        "$1 ($2) $3 $4-$5"
    ); // +1 (234) 567 89-00 ✔️

它适用于一个完整的数字,但在其他情况下失败,这里是其中的一些:

+12345678 // expected '+1 (234) 567 8', received '+1 (234) 567 8-'
+1234567  // expected '+1 (234) 567',   received '+1 (234) 567 -'
+123      // expected '+1 (23',         received '+1 (23)  -'

我错过了什么?

dldeef67

dldeef671#

不要重复发明轮子。看看谷歌的LibPhonenumber,它有一个javascript实现,可以“按你输入”格式化。你可以试试demo here
示例的输出:

****Parsing Result:****
{"country_code":1,"national_number":2345678900,"raw_input":"+12345678900 ","country_code_source":1}

****Validation Results:****
Result from isPossibleNumber(): true
Result from isValidNumber(): true
Result from isValidNumberForRegion(): false
Phone Number region: US
Result from getNumberType(): FIXED_LINE_OR_MOBILE

****Formatting Results:**** 
E164 format: +12345678900
Original format: +1 234-567-8900
National format: (234) 567-8900
International format: +1 234-567-8900
Out-of-country format from US: 1 (234) 567-8900
Out-of-country format from Switzerland: 00 1 234-567-8900
Format for mobile dialing (calling from US): +1 234-567-8900
Format for national dialing with preferred carrier code and empty fallback carrier code: (234) 567-8900

****AsYouTypeFormatter Results****
Char entered: + Output: +
Char entered: 1 Output: +1
Char entered: 2 Output: +1 2
Char entered: 3 Output: +1 23
Char entered: 4 Output: +1 234
Char entered: 5 Output: +1 234-5
Char entered: 6 Output: +1 234-56
Char entered: 7 Output: +1 234-567
Char entered: 8 Output: +1 234-567-8
Char entered: 9 Output: +1 234-567-89
Char entered: 0 Output: +1 234-567-890
Char entered: 0 Output: +1 234-567-8900
Char entered:   Output: +12345678900

这适用于所有(大多数?)国家,并确保您使用的格式是全球使用.如果我没有弄错,它是在Android手机中使用,最肯定的是在许多其他项目,我认为它可以被视为一个事实上的标准格式化数字.

ubby3x7f

ubby3x7f2#

你可以在replace方法中使用一个replacement函数。通过这个函数,你可以根据你所需要的条件来构建你的字符串:

function numberFormatter(number) {
  return number.replace(
    /^(\+\d{1})(\d{1,3})?(\d{1,3})?(\d{1,2})?(\d{1,2})?$/,
    (match, p1, p2, p3, p4, p5) => p1 + ' ' + (p2 ? '(' + p2 + (p2.length > 2 ? ')' : '') : '') + (p3 ? ' ' + p3 : '') + (p4 ? ' ' + p4 + (p4.length > 1 ? '-' : '') : '') + (p5 ? p5 : '')
  )
}

// Utils

// Tests which worked from your code
expect("+12345678900", "+1 (234) 567 89-00")
expect("+1234567890", "+1 (234) 567 89-0")
expect("+123456789", "+1 (234) 567 89-")
expect("+12345", "+1 (234) 5")

// Tests which work now
expect("+12345678", "+1 (234) 567 8")
expect("+1234567", "+1 (234) 567")
expect("+123", "+1 (23")

function expect(input, expectedResult) {
  const formattedNumber = numberFormatter(input)
  if (formattedNumber === expectedResult) {
    console.log(`PASSED: "${input}" -> "${expectedResult}"`);
  } else {
    console.error(`FAILED: "${input}" -> Expected: "${expectedResult}", Received: "${formattedNumber}"`);
  }
}

题外话:我对你的要求有点困惑。我认为替代品更有意义:

+1 (234) 567 89     -> +1 (234) 567 89  instead of +1 (234) 567 89-
+1 (23)             -> +1 (23)          instead of +1 (23

相关问题