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

134
Vistas
JS. Get part of date from string

I have this string '2020-10-20' Can i somehow get those numbers separately like this:

const [year, month, day] = '2020-10-20'.match(/\d\d\d\d/ what should i write there?)

Or any better approach exist?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You can split the string using a delimiter as follows

const [year, month, day] = '2020-10-20'.split("-")

then you would have year=2020 etc.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Using regex you can do something like this:

console.log('2020-10-20'.match(/\d+/g))

If you want to use Array.prototype.split, you can do something like this

console.log('2020-10-20'.split("-"))

about 4 years ago · Juan Pablo Isaza Denunciar

0

I'll add a little bit to the above solutions. If you want to get those values as number then use the map method.

const dateString = "2020-10-12";
const [year, month, date] = dateString.split("-").map(Number);
console.log(year, month, date);

Update

By the way, If you want to learn how to do that with regex, then here's how:

const dateString1 = "2020-10-10";
const dateString2 = "2020/10/10";
const dateString3 = "2020_10_10";

const pattern = /(\d{4}).(\d{2}).(\d{2})/;
 /* 
  * \d - matches digits 0 - 9
  * \d{4} - matches any 4 digits. e.g., 1234, 4587 ...
  * \d{2} - matches any 2 digits.
  * . - matches anything except new line ("\n"). For the
  * separator.
  * (anything-here) - anything inside () is called a capture
  * group.
  * and will be available in the result
  * */
 
 /*
  * console.log(pattern.exec(dateString2))
  * returns [ "2020/10/10", "2020", "10", "10" ]
  * now we need to slice the arrary from index 1 to 3
  * and we get [ "2020", "10", "10" ]
  * */
  
function parseDate(dateString) {
  // For invalid dateString we'll throw an error
  if(!pattern.test(dateString))
    throw new Error("Invalid date string");
  return pattern.exec(dateString).slice(1).map(Number);
}
  
console.log(parseDate(dateString1))
console.log(parseDate(dateString2))
console.log(parseDate(dateString3))

  

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