Skip to content

Instantly share code, notes, and snippets.

@waghcwb
Created June 15, 2020 16:56
Show Gist options
  • Save waghcwb/bc3a96935bb22e2441518be09e249228 to your computer and use it in GitHub Desktop.
Save waghcwb/bc3a96935bb22e2441518be09e249228 to your computer and use it in GitHub Desktop.
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