Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 1, 2022 10:43 pm GMT

Splitting String on Date Format Producing an Array

I had a need to parse a string with no clear delimiter except for a particular date, so I created this function to split the string based on the date format (M/D/YY, MM/DD/YYYY) within the string so I could then add my own delimiter to then break it up into an array.

function getStringArrayByDateFormat(str, pattern) {  const DELIMITER = '~';  let m, updatedText = str;  let uniqueMatches = [];  while ((m = pattern.exec(str)) !== null) {    if (m.index === pattern.lastIndex) {      pattern.lastIndex++;    }    m.forEach((match, groupIndex) => {      if (!uniqueMatches.includes(match)) {        uniqueMatches.push(match);      }    });  }  uniqueMatches.forEach((item) => {    const regex = new RegExp(`${item}`, 'g');    updatedText = updatedText.replace(regex, `${DELIMITER}${item}`);  })  const list = updatedText.split(DELIMITER).filter((s) => s.length > 0);  console.log(list);}

To call it

const DATE_PATTERN = /\d{1,2}\/\d{1,2}\/\d{2,4}/g;const textToSplit = `3/22/2022: This is a test comment 1 3/25/2022: This is a test comment 2 3/26/2022: This is a test comment 3 3/27/2022: This is a test comment 4`;getStringArrayByDateFormat(textToSplit, DATE_PATTERN);

After running this script, we get the following array, which we can loop over and render on the screen.

[    "3/22/2022: This is a test comment 1 ",     "3/25/2022: This is a test comment 2 ",     "3/26/2022: This is a test comment 3 ",     "3/27/2022: This is a test comment 4"]

Here is the fiddle for it.


Original Link: https://dev.to/briang123/splitting-string-on-date-format-producing-an-array-468l

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To