Created
September 29, 2022 23:10
-
-
Save TravisMullen/5903580a3cdcc96e71519dc58a3233d8 to your computer and use it in GitHub Desktop.
Truncate Text
This file contains 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
// truncate text | |
function trimMiddle (text, maxLength, div) { | |
let t | |
let d = div || ' ' | |
let l = text.length | |
let a | |
let b | |
if (l > maxLength) { | |
a = Math.floor((maxLength / 2) - 1) | |
b = (l - Math.ceil((maxLength / 2) + 1)) | |
t = text.substring(0, a) + | |
d + | |
text.substring(b, l) | |
} else { | |
t = text | |
} | |
return t | |
} | |
export function truncate (input, maxLength, char) { | |
let text | |
let edited | |
let max = maxLength || 30 | |
let start = 0 | |
let stop | |
let divider | |
let divSymbol = char || '…' | |
let alpha | |
let beta | |
if (!input) { | |
return | |
} | |
text = input | |
stop = text.length | |
divider = text.indexOf('-') | |
if (text.length > max) { | |
// break apart ALPHA - BETA | |
if (divider > -1) { | |
// remove all spaces from ALPHA | |
alpha = text.substring(start, divider) | |
.replace(/\s/g, '') | |
// truncate 1/3 of max | |
alpha = trimMiddle(alpha, Math.floor(max / 3), divSymbol) | |
// get BETA | |
beta = text.substring(divider, stop) | |
beta = trimMiddle(beta, Math.floor((max / 3) * 2), divSymbol) | |
edited = alpha + ' ' + beta | |
} else { | |
edited = trimMiddle(text, max, divSymbol) | |
} | |
} else { | |
edited = text | |
} | |
return edited | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment