0

I am scraping some data and trying to parse some strings into numbers

So for example, I have an object like "(7 years 1 month)" and I want to parse it to count total months.

This code works, but it's a bit messy. Is there an easier way to simplify it?

var str = "(7 years 1 month)"
function calculateMonths(str){
 var parseTime = /\d*/;
 var findMonths = /\d*\s\month/;
 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*\s\year/;
 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 
 }
asked Sep 23, 2017 at 13:11

1 Answer 1

1

you can just split the string using split(" ") which will return you an array, then loop over the array and add months based on years and month. something like this:

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

answered Sep 23, 2017 at 13:22
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.