This code demonstrates a different approach using Array#reduce
, highlighting unique techniques.
const str = 'Lorem ipsum dolor sit amet consectetur adipiscing elit';
const result = str.split(/\s+/); //split on any amount of whitespace
.reduce((acc, word) => {
const last = acc[acc.length - 1] ?? "";
const newLast = `${last} ${word}`.trim();
if (newLast.length > 15)
return acc.concat(word);
return acc.slice(0, -1)
.concat(newLast);
}, []);
console.log(result);
An alternative implementation can be achieved using only regular expressions:
/(?<=^|\s)\b.{1,15}\b(?=\s|$)/g
This regex matches up to 15 characters as long as they form complete words, avoiding partial matches within words or surrounding white spaces.
const regex = /(?<=^|\s)\b.{1,15}\b(?=\s|$)/g;
const str = 'Lorem ipsum dolor sit amet consectetur adipiscing elit';
const result = [...str.matchAll(regex)].flat();
console.log(result);
Check it out on Regex101
Here are a few examples illustrating how this method works:
Lorem ipsum dolor sit amet consectetur adipiscing elit
^ ^^ ^
|_________|| |
11 | |
| |
| + -> 15th character, but match cannot end due to next non-whitespace symbol
+ -> whitespace prevents match from ending here
Lorem ipsum dolor sit amet consectetur adipiscing elit
^^ ^
||____________|
| 14
|
+ -> Match cannot start on whitespace and must be preceded by whitespace