Home > Back-end >  Calculate number of days from string like '1y2m3d', '2m3d', '1y3d', &#
Calculate number of days from string like '1y2m3d', '2m3d', '1y3d', &#

Time:06-02

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? Thanks.

CodePudding user response:

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.
  • Related