Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

142
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!