JavaScript Regex将字符串解析为数字并进行一些归结



我正在刮一些数据,并试图将一些字符串分解为数字

因此,例如,我有一个像 "(7 years 1 month)"这样的对象,我想对其进行分析以计数总月份

此代码有效,但有点混乱。有没有更简单的方法来简化它?

var str = "(7 years 1 month)"
function calculateMonths(str){
        var parseTime = /d*/;
        var findMonths = /d*smonth/;
        var monthsTime = str.match(findMonths)
        if (monthsTime == null) {
            var months = 0
        } else {
            r = monthsTime[0];
            var y = r.match(parseTime)
            var months = y[0]
            return months
        }
    }
    function calculateYears(str){
        var parseTime = /d*/;
        var findYears = /d*syear/;
        var yearsTime = str.match(findYears);
        if (yearsTime == null) {
            var years = 0
        } else {
            r = yearsTime[0];
            var x = r.match(parseTime);
            var years = x[0];
        }
        return years  
    }

您只需使用split(")将字符串拆分,该字符串将返回您一个数组,然后循环循环,然后根据年和月添加数月。这样的东西:

var str = "(7 years 1 month)";
var arr = str.replace(/[()]/g, "").split(/s/), totalMonths = 0;
arr.forEach((x,index) => {
   switch(x){
   case 'years':
       totalMonths += +arr[index-1]*12;
       break;
   case 'month':
       totalMonths += +arr[index-1];
       break;
   }
})
console.log(totalMonths);

最新更新