Home > Back-end >  Find an element in an array that matches the regex given
Find an element in an array that matches the regex given

Time:04-12

I am having an array of different elements in the string format, I wanted to check whether an array contains date field in it. Currently I am thinking of using a date regex and then match it with all the elements in an array, but I am not sure of how to use that.

 let arr = ['SUPERMARKET', '465', 'S', 'Arroyo', 'Pkwy', 'Pasadena,', 'CA', '91105', '1', '1', '1', 'DOZ', 'FREE', 'RANGE', 'EGG', '$3.89', 'GV', 'ORGANIC', 'MILK', '2%', '$4.19', 'SBUX', 'FRENCH', 'ROAST', 'WL', '$8.99', 'SUBTOTAL', '$17.07', 'TOTAL', '$17.07', '$17.07', 'PURCHASE', '$17.07', 'VISA', 'DEBIT', '3991', 'Auth', '#140987', 'Exp', 'Date', '**/**', 'Lane', '#14', 'Cashier', '1409', '11/21/2019', '01:28', 'PMRef/Seq', '#140987', 'MRCH', '204650', 'Term=001', 'IC=CC', 'EPS', 'Sequence', '934518', 'ITEM', '1', 'H,', 'STEPHIE', '11/21/2019', '01:28', 'PM', '4130', '29', '1041', '2675']

 let dateRegex = "^([0]?[1-9]|[1|2][0-9]|[3][0|1])[./-]([0]?[1-9]|[1][0-2])[./-]([0-9]{4}|[0-9]{2})$"

CodePudding user response:

arr.filter(x=>x.match(whateEverRegex))

this will return every element that satisfies x.match(whateEverRegex)

CodePudding user response:

You can try this:

let arr = ['SUPERMARKET', '465', 'S', 'Arroyo', 'Pkwy', 'Pasadena,', 'CA', '91105', '1', '1', '1', 'DOZ', 'FREE', 'RANGE', 'EGG', '$3.89', 'GV', 'ORGANIC', 'MILK', '2%', '$4.19', 'SBUX', 'FRENCH', 'ROAST', 'WL', '$8.99', 'SUBTOTAL', '$17.07', 'TOTAL', '$17.07', '$17.07', 'PURCHASE', '$17.07', 'VISA', 'DEBIT', '3991', 'Auth', '#140987', 'Exp', 'Date', '**/**', 'Lane', '#14', 'Cashier', '1409', '11/08/2019', '01:28', 'PMRef/Seq', '#140987', 'MRCH', '204650', 'Term=001', 'IC=CC', 'EPS', 'Sequence', '934518', 'ITEM', '1', 'H,', 'STEPHIE', '11/12/2019', '01:28', 'PM', '4130', '29', '1041', '2675']

let dateRegex = /^([0]?[1-9]|[1|2][0-9]|[3][0|1])[./-]([0]?[1-9]|[1][0-2])[./-]([0-9]{4}|[0-9]{2})$/

arr.forEach(e => {
  if(dateRegex.test(e)) {
    console.log(e)
  }
})

Note:

  • The dates in your current data are "11/21/2019" of format mm/dd/yyyy, while the regex you use is of the format dd/mm/yyyy so the dd part in your dates('21') wont match the regex. I have changed the dates in this answer to match the regex.
  • OR you can change the regex to match the date(mm/dd/yyyy), by using: ^([0]?[1-9]|[1][0-2])[./-]([0]?[1-9]|[1|2][0-9]|[3][0|1])[./-]([0-9]{4}|[0-9]{2})$
  • You can use regex as they are if you place them between / instead of quotes "
  • Related