How to parse a duration string into seconds with Javascript?

后端 未结 5 1337
闹比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:38

    You can use this code to break your string into a number, followed by a unit string:

    function getPieces(str) {
        var pieces = [];
        var re = /(\d+)[\s,]*([a-zA-Z]+)/g, matches;
        while (matches = re.exec(str)) {
            pieces.push(+matches[1]);
            pieces.push(matches[2]);
        }
        return(pieces);
    }
    

    Then function returns an array such as ["1","day","2","hours","3","minutes"] where alternating items in the array are the value and then the unit for that value.

    So, for the string:

    "1 day, 2 hours, 3 minutes"
    

    the function returns:

    [1, "day", 2, "hours", 3, "minutes"]
    

    Then, you can just examine the units for each value to decide how to handle it.

    Working demo and test cases here: http://jsfiddle.net/jfriend00/kT9qn/. The function is tolerant of variable amounts of whitespace and will take a comma, a space or neither between the digit and the unit label. It expects either a space or a comma (at least one) after the unit.

提交回复
热议问题