regex - How to parse a duration string into seconds with Javascript? -


i'm trying parse user input string duration (into seconds) javascript.

here example inputs i'd able deal with:

  • "1 hour, 2 minutes"
  • "1 day, 2 hours, 3 minutes"
  • "1d 2h 37m"
  • "1 day 2min"
  • "3days 20hours"

the key components 1) days, 2) hours 3) minutes, components may not included.

my plan of attack use .match , regex. long can first letter of word, i'll know preceding number , able handle different formats of words (e.g. hours, hour, hr, h). however, since i'm learning regex this, it's turned out more complicated thought.

any or suggestions appreciated!

is order of days/hours/minutes in string guaranteed? if not, may easier separate regex each. this?

function getseconds(str) {   var seconds = 0;   var days = str.match(/(\d+)\s*d/);   var hours = str.match(/(\d+)\s*h/);   var minutes = str.match(/(\d+)\s*m/);   if (days) { seconds += parseint(days[1])*86400; }   if (hours) { seconds += parseint(hours[1])*3600; }   if (minutes) { seconds += parseint(minutes[1])*60; }   return seconds; } 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -