Created
June 15, 2020 16:56
-
-
Save waghcwb/bc3a96935bb22e2441518be09e249228 to your computer and use it in GitHub Desktop.
Script that breaks a string into lines based on a maximum attribute
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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