Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

105
Views
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?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

this return an array of matches

result = string.match(re)
about 4 years ago · Juan Pablo Isaza Report

0

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('-') )

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!