Skip to content

Instantly share code, notes, and snippets.

@zgover
Last active April 28, 2021 10:48
Show Gist options
  • Save zgover/8f2520741d26b2ac1b6a58578c47e4a8 to your computer and use it in GitHub Desktop.
Save zgover/8f2520741d26b2ac1b6a58578c47e4a8 to your computer and use it in GitHub Desktop.
[JS WordWrap] Strip and ellipsize text characters exceeding the max
/**
* This utility function shortens passed text to desired length
*
* e.g. wordWrap(str, { maxWidth: 150, moreIndication: '...' })
*
* @param {String} str text that requires shortening
* @param {Object} opt the wrapping options
* {Number} maxWidth the max width of the text
* {string} moreIndication indicator to append to the end
*/
export default function wordWrap (str, opt = {}) {
let { maxWidth, moreIndication } = {
maxWidth = 150,
moreIndication = '...',
...opt
}
let newLineStr = '\n'
let done = false
let found = false
let len = str.length
let res = ''
do {
found = false
// Inserts new line at first whitespace of the line
for (let i = maxWidth - 1; i >= 0; i--) {
if (testWhite(str.charAt(i))) {
res = [str.slice(0, i), newLineStr].join(moreIndication)
str = str.slice(maxWidth - 1, i + 1)
found = true
break
}
}
// Inserts new line at maxWidth position, the word is too long to wrap
if (!found) {
res = [str.slice(0, maxWidth), newLineStr].join(moreIndication)
str = str.slice(maxWidth)
}
if (str.length < maxWidth) {
done = true
}
} while (!done)
return res.trim() === moreIndication ? '' : res.trim()
}
function testWhite (x) {
let white = new RegExp(/^\s$/)
return white.test(x.charAt(0))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment