从分钟和小时的字符串中计算分钟

时间:2018-07-11 09:43:29

标签: javascript typescript

我有一个函数,它需要一小时和几分钟的字符串,并将其转换为分钟。这绝对可以,但是如果收到的参数只有几分钟或几小时呢?例如

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]
}

3 个答案:

答案 0 :(得分:3)

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

并且(res[0] || 0)的部分将在0res[0]null时返回值undefined

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"));

答案 1 :(得分:3)

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

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

答案 2 :(得分:2)

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

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));

相关问题