'Regex matching dates in a string in Javascript

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)]

This returns an array of two arrays. Is there a way to consolidate this into 1 array?

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

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



Solution 1:[1]

this return an array of matches

result = string.match(re)

Solution 2:[2]

This is a function to parse the string encoding those two year values and return the inner years as items of an array:

let o = parseYearsInterval('2016-2022');
console.log(o);

function parseYearsInterval(encodedValue){
  var myregexp = /(\d{4})-(\d{4})/;
  var match = myregexp.exec(encodedValue);
  if (match != null) {
    let d1 = match[1];
    let d2 = match[2];
    //return `[${d1}, ${d2}]`;
    let result = [];
    result.push(d1);
    result.push(d2);
    return result;
  } else {
    return "not valid input";
  }
}

I think there are better ways to do that like splitting the string against the "-" separator and return that value as is like:

console.log ( "2016-2022".split('-') )

Solution 3:[3]

Just do a split if you know that only years are in the string and the strucutre isn't changing:

let arr = str.split("-");

Solution 4:[4]

Question

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

This returns an array of two arrays. Is there a way to consolidate this into 1 array?

Solution

You may simply flat the result of matchAll.

let string = '2016-2022'
let re = /\d{4}/g
console.log([...string.matchAll(re)].flat())

Alternative

If your structure is given like "yyyy-yyyy-yyyy" you might consider a simple split

console.log('2016-2022'.split('-'))

Solution 5:[5]

var str = '2016-2022';
var result = [];
str.replace(/\d{4}/g, function(match, i, original) {
    result.push(match);
    return '';
});
console.log(result);

I also wanted to mention, that matchAll does basicly nothing else then an while exec, that's why you get 2 arrays, you can do it by yourself in a while loop and just save back what you need

var result = [];
var matches;
var regexp = /\d{4}/g;
while (matches = regexp.exec('2016-2022')) result.push(matches[0]);
console.log(result);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Simone Celia
Solution 2 Diego De Vita
Solution 3 John_H_Smith
Solution 4 Lain
Solution 5