Skip to content

Instantly share code, notes, and snippets.

@PradipShrestha
Created September 15, 2021 02:12
Show Gist options
  • Select an option

  • Save PradipShrestha/8ea78b989b7cfa3e43cde0784a2dfeae to your computer and use it in GitHub Desktop.

Select an option

Save PradipShrestha/8ea78b989b7cfa3e43cde0784a2dfeae to your computer and use it in GitHub Desktop.
Word wrapping of given input string such that every line cannot exceed max length and breaking word is not allowed.
const wrap = (text, length) => {
const words = text.split(' ')
let line = ''
let lastWord = ''
const result = []
for (let i = 0; i < words.length; i++) {
if (length > (words[i].length + line.length)) {
line += words[i] + ' '
continue
}
if (words[i].length >= length) {
result.push(line)
continue
}
result.push(line.trimEnd())
line = words[i] + ' '
}
if (line.length) {
result.push(line.trimEnd())
}
return result
}
const text = 'It\'s fairly primitive - it splits on spaces, tabs and dashes. It does make sure that dashes stick to the ' +
'word before it (so you don\'t end up with stack-overflow) though it doesn\'t favour moving small hyphenated words to ' +
'a newline rather than splitting them. It does split up words if they are too long for a main line. Check if it works.'
const words = wrap(text, 19)
console.log(words)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment