Splitting String on Date Format Producing an Array
Brian Gaines
Posted on April 1, 2022
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.
💖 💪 🙅 🚩
Brian Gaines
Posted on April 1, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
beginners Artificial Intelligence (AI) holds immense promis, but it also faces several challenges and risks
August 6, 2024