根据分钟和小时的字符串计算分钟



我有一个函数,它占用一个小时和分钟的字符串,并将其转换为分钟。这绝对有效,但如果收到的争论只有几分钟或一小时呢。例如

const str = "1 hour 5 mins"; // works
const str = "1 hour"; // doesn't work
const str = "5 mins"; //  doesn't work
const str = "1 hour 5 mins";
this.calculate(str);
calculate(str) {
let res = str.match(/d+/g).map(Number);
return res[0] * 60 + res[1]
}

您需要一个更智能的正则表达式,能够区分小时值和分钟值:

const calculate = (s) => {
const matches = /(?:(d+) hours?)? ?(?:(d+) mins?)?/.exec(s);

return Number(matches[1] || 0) * 60 + Number(matches[2] || 0);
};
console.log(calculate('1 hour 5 mins')); // 65
console.log(calculate('2 hours 1 min')); // 121
console.log(calculate('3 hours')); // 180
console.log(calculate('10 mins')); // 10

您可以检查如果您的字符串包含hour,则第一个值需要与60相乘,否则它应该使用相同的值。

res[0]nullundefined时,该部分的(res[0] || 0)将返回值0

function calculate(str) {
let multiplier = str.includes("hour") ? 60 : 1;
let res = str.match(/d+/g).map(Number);
return (res[0] || 0) * multiplier + (res[1] || 0);
}
console.log(this.calculate("1 hour 5 mins"));
console.log(this.calculate("1 hour"));
console.log(this.calculate("5 mins"));
console.log(this.calculate("2 hours 5 mins"));

如果您查找特定项并提取一个数字/单位对,则可以使用捕获组进行计算。

const t1 = '1 hour 5 mins';
const t2 = '1 hour';
const t3 = '5 mins';
const t4 = '2 hours 1 min';
const parseDuration = (s) => {
var matches = s.match(/(d+s?hours?)?s?(d+s?mins?)?/);
var total = matches[1] ? parseInt(matches[1])*60 : 0;
total += matches[2] ? parseInt(matches[2]) : 0;
return total;
}
console.log(parseDuration(t1));
console.log(parseDuration(t2));
console.log(parseDuration(t3));
console.log(parseDuration(t4));

最新更新