Morgan Allen Morgan Allen - 5 months ago 44
Javascript Question

Javascript Regex parsing a string to numbers and doing some calucations

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

Dij Dij
Answer Source

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) => {
   case 'years':
       totalMonths += +arr[index-1]*12;
   case 'month':
       totalMonths += +arr[index-1];


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download