0

Following up from this thread, im trying to make this work

JavaScript regular expression to match X digits only

string = '2016-2022'
re = /\d{4}/g
result = string.matchAll(re)

The goal is to return [2016, 2022]

However it doesn't look like this is returning the desired results

I'm new to regular expression. What am I doing wrong?

Morgan Allen
  • 3,065
  • 5
  • 50
  • 81
  • do you just need to test if the string contains the regex or do you need the output of the match? – John_H_Smith Apr 08 '22 at 12:43
  • you're trying to match `xxxx` like this, `^` is starting of string and `$` marks end of string – boxdox Apr 08 '22 at 12:43
  • @John_H_Smith the goal is to have an array of [2016, 2022] – Morgan Allen Apr 08 '22 at 12:44
  • @MorganAllen - Then get rid of the beginning-of-input and end-of-input assertions (`^` and `$`), and add the global flag: `re = /\d{4}/g`. (And use [`matchAll`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll) or a loop.) (Also, be sure to *declare* your variables.) – T.J. Crowder Apr 08 '22 at 12:45
  • @T.J.Crowder thanks for the advice, just updated the question but getting an emptry result – Morgan Allen Apr 08 '22 at 12:47
  • @MorganAllen - Please see the documentation I linked above for how to use the `matchAll` results. – T.J. Crowder Apr 08 '22 at 12:48
  • @T.J.Crowder this returns an array of two arrays. Is there a way to make it into one array? – Morgan Allen Apr 08 '22 at 12:50
  • @MorganAllen - Yes, you can [`map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) or loop through the match results with `for-of` to build your own array. – T.J. Crowder Apr 08 '22 at 12:51

0 Answers0