Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

108
Vistas
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 Respuestas
Responde la pregunta

0

this return an array of matches

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

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda