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:
- “1 hour, 2 minutes”
- “1 day, 2 hours, 3 minutes”
- “1d 2h 37m”
- “1 day 2min”
- “3days 20hours”
The key components are 1) days, 2) hours 3) minutes, but some components may not always be included.
My plan of attack is to use .match and regex. As long as I can get the first letter of the word, I’ll know what the preceding number is for and be able to handle all the different formats of the words (e.g. hours, hour, hr, h). However, since I’m learning regex for this, it’s turned out to be much more complicated than I thought.
Any help or suggestions would be greatly appreciated!
Is the order of days/hours/minutes in your string guaranteed? If not, it may be easier to just do a separate RegEx for each. Something like this?