user3872094
user3872094

Reputation: 3351

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

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

Upvotes: 1

Views: 384

Answers (2)

Stratis Dermanoutsos
Stratis Dermanoutsos

Reputation: 787

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.

Upvotes: 4

Nick
Nick

Reputation: 147146

You could match against this regex:

[^\s].{1,29}((?=\s|$)|(?<=[.,]))

which looks for a non-space character ([^\s]), and then up to 29 other characters (.{1,29}) which either:

  1. are followed by a space or end-of-line (?=\s|$); or
  2. end with a comma or full-stop (?<=[.,])

let x='Lorem ipsum dolor sit amet. Excepteur cuptat non proident, consectetur adipiscing elite detailo';

let splitString = x.match(/[^\s].{1,29}((?=\s|$)|(?<=[.,]))/g);

console.log(splitString);

Upvotes: 4

Related Questions