How to parse a duration string into seconds with Javascript?

后端 未结 5 1329
闹比i
闹比i 2020-12-28 23:42

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:

5条回答
  •  心在旅途
    2020-12-29 00:43

    You can use optional substrings in the regex to match any combination as you describe:

    /(\d+)\s*d(ays?)?\s*(\d+)\s*h(ours?)?\s*(\d+)\s*m(in(utes?)?)?/
    

    This requires at least a d, h, and m but accepts common shortenings.

提交回复
热议问题