0

Consider the following regex -- /\d+([a-z]+)\d+/

and the following test string -- 345345dffdfd34534

example code --

var s = '345345dffdfd34534';
var result = s.match(/\d+([a-z]+)\d+/);

Why does javascript return an array instead of just the letters dffdfd that match the capturing group when I try to match the string with regex ? I know it's not a big deal but is this how it is supposed to work or am I doing somethinig wrong?

EDIT: I am not asking how to access the capturing group. I know it is just a case of looking up the array. But why does JS still return two results instead of whats just part of the capturing group?

charsi
  • 2,917
  • 22
  • 40
  • The "([a-z]+)" capturing group, groups multiple tokens together and creates a capture group for extracting a substring or using a backreference. – Jonathan Newton Aug 16 '16 at 12:18
  • 3
    [Why not read some documentation?](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match) – Pointy Aug 16 '16 at 12:18
  • 1
    @charsi the API returns an array because that's what it's defined to do. The captured groups are present in the array starting with index 1. Index 0 always holds the *entire* match. – Pointy Aug 16 '16 at 12:25
  • From the docs : *An Array containing the **entire match** result **and** any parentheses-captured matched results* - pretty clear. Feel a bit dumb now. – charsi Aug 16 '16 at 12:28

0 Answers0