I want to split a string based on 30 character limit and the catch here is it should get broken on a period(.) or a comma(,) or a space( ). i.e., the string length of 30 or a delimiter whichever comes first. I tried with the match using regex, this splits well, but not with a delimiter.
For example, Here is my sample code.
let x='Lorem ipsum dolor sit amet. Excepteur cuptat non proident, consectetur adipiscing elite detailo';
let splitString = x.match(/.{1,30}/g);
console.log(splitString);
Here the output I get is
[
"Lorem ipsum dolor sit amet. Ex",
"cepteur cuptat non proident, c",
"onsectetur adipiscing elite de",
"tailo"
]
But I want this to happen using a comma or period or a space as a delimiter. Expected output is
[
"Lorem ipsum dolor sit amet.",
"Excepteur cuptat non proident,",
"consectetur adipiscing elite",
"detailo"
]
>Solution :
let x='Lorem ipsum dolor sit amet. Excepteur cuptat non proident, consectetur adipiscing elite detailo';
let splitString = x.match(/.{1,30}[\.\s,]/g).map(item => item.trim());
const remaining = x.replace(splitString.join(' '), '');
splitString = [...splitString, remaining.trim()]
console.log(splitString);
Edit:
I removed the trailing spaces in the substrings. Don’t know if it’s necessary but there is the exact wanted result now.