Last active
July 27, 2017 22:08
-
-
Save TravisMullen/a23b00537c685af0b897175ee16a0725 to your computer and use it in GitHub Desktop.
Trim Label
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
// truncate text | |
function trimMiddle (text, maxLength, div) { | |
const d = div || ' ' | |
const l = text.length | |
let t | |
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 | |
} | |
// function subscript (text, script) { | |
// const prefix = | |
// return | |
// } | |
export function truncate (input, maxLength, char) { | |
const start = 0 | |
const max = maxLength || 30 | |
const divSymbol = char || '…' | |
let text | |
let edited | |
let stop | |
let divider | |
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) | |
// remove leading space from BETA | |
// if (beta.indexOf(' ') === 0) { | |
// beta = beta.substring(1, beta.length); | |
// } | |
// truncate 2/3 of max | |
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