JS transform with regEx -- help required please

I would like to format phone numbers with a JS transform and using regEx…
… and started out with a simple example, which does not seem to work.

(function(phoneNumber) {
  if (phoneNumber.substr(0, 2) == "04") {
    var result = phoneNumber.replace(/(\d{4}\d{3}\d{3})/g, '$1 $2 $3');
  } else {
    var result = phoneNumber.replace(/(\d{2}\d{4}\d{4})/g, '$1 $2 $3');
  }
  return result
})(input)

Desired outcome:
in: 0411511002
out: 0411 511 002

and

in: 0754346543
out: 07 5434 6543

Any hints appreciated.

I think each section of numbers needs to have its own capture parentheses, so they can be used with the $1 $2 $3. Like phoneNumber.replace(/(\d{4})(\d{3})(\d{3})/g, '$1 $2 $3');

From here:

Matches ‘x’ and remembers the match, as the following example shows. The parentheses are called capturing parentheses.

The ‘(foo)’ and ‘(bar)’ in the pattern /(foo) (bar) \1 \2/ match and remember the first two words in the string “foo bar foo bar”. The \1 and \2 in the pattern match the string’s last two words. Note that \1, \2, \n are used in the matching part of the regex. In the replacement part of a regex the syntax $1, $2, $n must be used, e.g.: ‘bar foo’.replace( /(…) (…)/, ‘$2 $1’ ). $& means the whole matched string.

1 Like

Thanks… sometimes I really wonder about myself – getting old I guess :smiley:

So yes, the groups were not braced…

What I noticed (and have to investigate this) is that I need $2 $3 $4 to get the whole number. $1 returns the lot; but usually $0 returns the lot.

1 Like