I\'m trying to parse a user input string for duration (into seconds) with Javascript.
Here are some example inputs that I\'d like to be able to deal with:
A more general version of the accepted answer that accepts months and seconds as well.
const getSeconds = str => {
let seconds = 0;
let months = str.match(/(\d+)\s*M/);
let days = str.match(/(\d+)\s*D/);
let hours = str.match(/(\d+)\s*h/);
let minutes = str.match(/(\d+)\s*m/);
let secs = str.match(/(\d+)\s*s/);
if (months) { seconds += parseInt(months[1])*86400*30; }
if (days) { seconds += parseInt(days[1])*86400; }
if (hours) { seconds += parseInt(hours[1])*3600; }
if (minutes) { seconds += parseInt(minutes[1])*60; }
if (secs) { seconds += parseInt(secs[1]); }
return seconds;
};