javascriptregexstringreplacedays

How to calculate number of days from a string like '1y2m3d', '2m3d', '1y3d', '1y' or simply '3d'


I want to create a filtering system in JavaScript. I have a string that contains a number of years, months, and days. I would like to transform this string to number of days format. So:

1y1m2d = 1*365+1*30+2
1y2d = 1*365+2

and so on. I have tried to create a regex for that:

/(\d+y)?(\d+m)?(\d+d)?/

However, the problem with this solution is that I am not able to know whether a group is for years, months, etc.

The second solution I tried was to use .replace and then pass it through math.eval() but this did not work for me. I am not sure why.

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

In this scenario, we can assume that the number of days in a month is a constant, for example 30 days.

What am I doing wrong?


Solution

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