Home > database >  from a string that contains a date range
from a string that contains a date range

Time:03-03

when you born in 1995 you also can make a friend 2002 but also not exactly than 1788. The result should be [1995, 1788]

CodePudding user response:

Check this snippet, I used a regex to extract all the numbers from 0 to 9999 from the text, then filtered all the matches to get only numbers inside the given range.

// This function will check if a value is inside a given range
const isInRange = (lowerBound,upperBound,value) => { 
    return (lowerBound<=value && value<=upperBound);
};

// This is the main function that takes the input text as a parameter and retuns an array with all the years that was mentioned in the text and also are in the accepted range
const getArrayOfYears = (text) => { 
    const yearRegex = /[0-9]{1,4}/g;
    const matches = text.match(yearRegex); // This is a list of all the numbers in the list 
    
    let res = [];
    matches.forEach( (item) =>{
        const year = parseInt(item)
        if(isInRange(1900,2099,year)) { 
            res.push(year);
        }
    });
    
    return res;
}

const testText = "Usually people who were born in 1995 can find they first job not later than in 2020 but also not earlier than in 2012. Number 11999 is not included in the result because it's too big. It is out of range between 1900 and 2099.";

// and here is the final result
console.log(getArrayOfYears(testText))

CodePudding user response:

I'm not sure this solution is better than the one from @Ali but it's a different approach, where everything is done through the RegExp. I'll admit, the RegExp is a bit of a mouthful to cover edge cases...

const getDates = (text) => {
  const datePattern = new RegExp(/(?:^|[^\d])((?:19|20)\d{2})(?:$|[^\d])/, 'g');  
  const results = [];
  let match;
  while ((match = datePattern.exec(text)) !== null) {
    results.push(parseInt(match[1]));
  }
  return results;
};
  • Related