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?
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 stringx
standing for the match value, index
is the start match position, and source
is the input string valuey
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.