Is there a better way to extract information from a string?

  • A+
Category:Languages

Let's say I have an array of strings, and I need specific info from them, what would be an easy way to do that?

Suppose the array was this

let infoArr = [   "1 Ben Howard 12/16/1988 apple",   "2 James Smith 1/10/1999 orange",   "3 Andy Bloss 10/25/1956 apple",   "4 Carrie Walters 8/20/1975 peach",   "5 Doug Jones 11/10/1975 peach" ]; 

Let's say I wanted the date extracted and saved into another array, well I could make a function like this

function extractDates(arr){   let dateRegex = /(/d{1,2}//){2}/d{4}/g, dates = "";   let dateArr = [];   for(let i = 0; i<arr.length; i++){     dates = /(/d{1,2}//){2}/d{4}/g.exec(arr[i])     dates.pop();     dateArr.push(dates);   }   return dateArr.flat(); } 

Although this works, it is clunky and requires I pop() because it will return an array of arrays, ie: ["12/16/1988", "16/"], plus I need to call flat afterwards.

Another option would be to substring the strings, with a given position, where I need to know a regex pattern.

function extractDates2(arr){   let dates = [];   for(let i = 0; i<arr.length; i++){     let begin = regexIndexOf(arr[i], /(/d{1,2}//){2}/d{4}/g);     let end = regexIndexOf(arr[i], /[0-9] /g, begin) + 1;        dates.push(arr[i].substring(begin, end));   }   return dates;  } 

And of course have a regexIndexOf function

function regexIndexOf(str, regex, start = 0){   let indexOf = str.substring(start).search(regex);   indexOf = (indexOf >= 0) ? (indexOf + start) : -1;   return indexOf; } 

Again this function also works, but it seems like an awful lot just to extract something simple. Is there an easier way to extract data into an array?

 


One option would be to join the strings by a separator that won't be matched, like ,, then just perform the global match to get an array of dates from it:

let infoArr = [   "1 Ben Howard 12/16/1988 apple",   "2 James Smith 1/10/1999 orange",   "3 Andy Bloss 10/25/1956 apple",   "4 Carrie Walters 8/20/1975 peach",   "5 Doug Jones 11/10/1975 peach" ]; const result = infoArr   .join(',')   .match(/(/d{1,2}//){2}/d{4}/g); console.log(result);

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: