Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

144
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda