DEV Community

Cover image for Splitting String on Date Format Producing an Array
Brian Gaines
Brian Gaines

Posted on

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);

}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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"
]
Enter fullscreen mode Exit fullscreen mode

Here is the fiddle for it.

Top comments (0)