0
votes

What's working: I'm using a regex similar to the one below for phone numbers (the actual regex is here) that can grab extensions as an optional 4th group. The regex itself is working fine for the first three groups as shown below

"555-555-5555 x214".replace(/([\d]{3})-([\d]{3})-([\d]{4})(?: +x([\d]+))?/, "$1-$2-$3");
// returns 555-555-5555

What I'm looking for: I can't find the syntax for the replace string to insert the phone extension preceded by a x ONLY if the 4th group is captured. In my real regex, the phone extension could be marked by few different character designations which I would like to simply replace with an "x".

If I use:

"555-555-5555 x214".replace(/([\d]{3})-([\d]{3})-([\d]{4})(?: +x([\d]+))?/, "$1-$2-$3 x4");
// returns 555-555-5555 x214

"555-555-5555".replace(/([\d]{3})-([\d]{3})-([\d]{4})(?: +x([\d]+))?/, "$1-$2-$3 x4");
// will return 555-555-5555 x

In the last example, I get the "x" (which I'm not surprised by), so I'm looking for the syntax to only add the "x" plus group 4 if something was captured.

Is this possible with String.replace? If not, is there a more efficient way to replace these groups with a formatted number type once I've identified their parts?

1

1 Answers

2
votes

The String#replace function can also take a function as a 2nd argument, which can be more expressive that a string.

For example:

"555-555-5555".replace(/(\d{3})-(\d{3})-(\d{4})(?: +x(\d+))?/, replacer);

function replacer(match, p1, p2, p3, p4, offset, string) {
  return `${p1}-${p2}-${p3}` + (p4 ? ` x${p4}` : '')
}

See MDN documentation for more details :)

Note that your regex needed some modifications. Play with it here: https://regex101.com/r/rtJYTw/1