Yury Zaitsev
by emilcieslar
JavaScript
function cutLines(text, length) {
const textLines = text.split('\n');
return textLines.map(line => {
if (/\w/.test(line.charAt(length)) && /\w/.test(line.charAt(length - 1))) {
// we are in the middle of the word
const matchNonWordBeforeCurrentWord = line.substr(0, length).match(/(^.*?\W)\w+$/);
return matchNonWordBeforeCurrentWord ? matchNonWordBeforeCurrentWord[1] : '';
} else {
return line.substr(0, length);
}
}).join('\n');
}
const text = `Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.`;
const result = cutLines(text, 25);
console.log(result);