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]/gmatches all occurrences ofyormordin the string- There are three arguments used in the callback function:
xstanding for the match value,indexis the start match position, andsourceis the input string value - If
yis matched, the replacement is*360andif the match is not at the end of string, ifmis matched, the replacement is*30and, and ifdis matched, no multiplier is added. (index !== source.length-1 ? ' ' : '')checks if the match is at the end of string, and addsif necessary. It works like this because the match is always a single char.
