javascript replace with regex groups

ishan vimukthi
Jun 16, 2021
groups  of  people

This is a problem that I got from a friend. His problem was to fix an incorrectly typed name “Surname FirstName” by swapping the 2 names like “FirstName SurName”

For example:-

“Kandage Ishan” to “Ishan Kandage”

“Perera Nimal” to “Nimal Perera”

We can solve this easily by using javascript replace and a simple regex like this

“Kandage Ishan”.replace(/(\w+) (\w+)/,"$2 $1");

See the magic happen by using regex groups. In the replacement string, we can refer to any group that we matched in our regex using syntax $RegexGroupNumber.

And we have a bonus feature called named groups you can name the groups in regex expression and use them in the replacement string instead of giving a number value using syntax ?<RegexGroupName>.

Eg :-
“Kandage Ishan”
.replace(
/(?<firstName>\w+) (?<secondName>\w+)/
,
"$<secondName> $<firstName>"
);

--

--