An Interest In:
Web News this Week
- April 3, 2024
- April 2, 2024
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
April 1, 2022 10:43 pm GMT
Original Link: https://dev.to/briang123/splitting-string-on-date-format-producing-an-array-468l
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:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To