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

143
Visualizações
Calculate number of days from string like '1y2m3d', '2m3d', '1y3d', '1y' or simply '3d'

I want to create some filtering system to my grid in javascript. My issue is that I have a string that contains number of years, months and days. I would like to transform this string to number of days format. I.e. 1y1m2d = 1*365+1*30+2, 1y2d = 1*365+2 or another combination like this.

I'm not exactly sure on how to handle this. I've tried to create a regex for that, however I don't know how to distinct whether group is for year or months etc.

Regex looks like this - /(\d+y)?(\d+m)?(\d+d)?/ however with this solution the problem is that I'm not able to know whether group is for years, months etc.

The second solution I tried was to use .replace and then pass it through math.eval() but this proved not working for me, I'm not sure why.

let result = stringFormat.replace(/y|m|d/, function (x) {
  return x === 'y' ? '*365' : x === 'm' ? '*12' : '*30';
});

What do you think about this? What would be the best approach here?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use

const stringFormat = '1y1m2d'; 
let result = stringFormat.replace(/[ymd]/g, function (x, index, source) {
  return (x === 'y' ? '*365' : x === 'm' ? '*30' : '')+(index !== source.length-1 ? '+' : '');
});
console.log(result) // => 1*365+1*30+2

Notes:

  • /[ymd]/g matches all occurrences of y or m or d in the string
  • There are three arguments used in the callback function: x standing for the match value, index is the start match position, and source is the input string value
  • If y is matched, the replacement is *360 and + if the match is not at the end of string, if m is matched, the replacement is *30 and +, and if d is matched, no multiplier is added.
  • (index !== source.length-1 ? '+' : '') checks if the match is at the end of string, and adds + if necessary. It works like this because the match is always a single char.
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