Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

split string based on character limit and a period

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
  "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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading