Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Script that breaks a string into lines based on a maximum attribute
function maxWordsPerLine(str, max = 30) {
const result = [];
let counter = 1;
let tempArr = [];
for (const [index, letter] of str.split('').entries()) {
if (counter === max + 1) {
counter = 1;
result.push(tempArr);
tempArr = [];
} else {
tempArr.push(letter);
counter = counter + 1;
}
}
const toArray = () => result.map((r) => r.join('').trim())
return {
toArray() {
return toArray()
},
toString() {
const arr = toArray()
return arr.join('\n')
}
}
}
// usage
const maxWords = maxWordsPerLine('Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ad adipisci doloremque ea earum explicabo impedit iste, minus quos repudiandae sit? Ad at consectetur dicta et eveniet illum ipsa quisquam repellendus!', 10);
console.warn('maxWords:', maxWords.toArray());
console.warn(maxWords.toString());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment