Duc Trinh's tech nuggets

Duc Trinh's tech nuggets

Regex accessing unnamed capturing group

Duc Trinh's photo
Duc Trinh
·May 8, 2021·

1 min read

So I was solving this problem called String incrementer the other day: codewars.com/kata/54a91a4883a7de5d7800009c

The idea is simple: use Regex capturing group to separate the words & the number apart and modify the number. However, codewars's javascript engine does not support named capturing group yet so I need to go with the version below:

  let res = ''
  let regex = /([A-Za-z]*)(\d*)/g;
  let found = regex.exec('foo099');

By running this, the found variable will return

image.png

and you could access the capturing groups using index (so the first group will be found[1], and so on). By using named capturing group, the found.groups property will be populated using an object with key as the name and value as the matched group. This definitely makes the code more readable.

You can read more about named capturing group for ES2018 here: 2ality.com/2017/05/regexp-named-capture-gro..