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

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

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