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:
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.