0

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 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

updated the sample regex, missed that when trying to simplify it, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.