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)
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');
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.