简体   繁体   中英

Why is match returning the whole string as the first element in the array?

Let's say I have this string:

'1234*321*123'

And I want to get each group of digits as an element in an array.

So I used this:

'1234*321*123'.match(/^(\d{4})\*(\d{3})\*(\d{3})$/);

But that's returning ["1234*321*123", "1234", "321", "123"] , when I was expecting ["1234", "321", "123"] .

Why, if only the digit groups are enclosed within capturing groups, does match return the whole string as the first element of the array?

Zeroth element is always the full match. First element is the first capture, second element is the second capture, etc. If you just want all the captures without the full match, you can use result.slice(1) .

If you are asking "Why is the first element the full match?" :

  • It's just the way match works.
  • It parallels $0 vs. $1 , $2 ... in older languages.

When you use () for matching, it gives both the specific components and the full string. For your desired result, use this:

'1234*321*123'.match(/\d+/g);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM