Skip to content

Instantly share code, notes, and snippets.

@audionerd
Created August 16, 2018 02:58
Show Gist options
  • Save audionerd/72394e21b38613190f61b74b2331666b to your computer and use it in GitHub Desktop.
Save audionerd/72394e21b38613190f61b74b2331666b to your computer and use it in GitHub Desktop.
-- via https://stackoverflow.com/questions/5723154/truncate-a-string-in-the-middle-with-javascript
-- https://stackoverflow.com/questions/831552/ellipsis-in-the-middle-of-a-text-mac-style/36470401#36470401
function truncateMiddle (str, maxLength, separator)
maxLength = maxLength or 30
separator = separator or "…"
if (maxLength < 1) then return str end
if (string.len(str) <= maxLength) then return str end
if (maxLength == 1) then return string.sub(str, 0, 1) .. separator end
midpoint = math.ceil(string.len(str) / 2)
toremove = string.len(str) - maxLength
lstrip = math.ceil(toremove / 2)
rstrip = toremove - lstrip
return string.sub(str, 1, midpoint - lstrip) .. separator .. string.sub(str, 1 + midpoint + rstrip)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment