Last active
February 22, 2023 14:59
-
-
Save bgorkem/5667bd12a597cc43ea15 to your computer and use it in GitHub Desktop.
truncation from the middle of the string..
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
/** | |
* this function will crop any given text to the size of the given target | |
* will crop in the middle | |
**/ | |
function cropMiddle(target, text) { | |
var input, | |
inputFontStyle, | |
ellipsisWidth, | |
maxWidth, | |
cutPoint; | |
// select input, set value | |
input = target; | |
input.value = text; | |
inputFontStyle = window.getComputedStyle(input, null).getPropertyValue('font'); | |
// calculate max width together with ellipsis | |
ellipsisWidth = getTextWidth('...', inputFontStyle); | |
maxWidth = (input.clientWidth - ellipsisWidth); | |
/** recursively splices text from the middle by one char at a time | |
* until text fits to given maxWidth | |
* then inserts the ellipsis in the middle | |
**/ | |
function sliceIfNotFitting() { | |
var textWidth = getTextWidth(text, inputFontStyle); | |
if (textWidth > maxWidth) { | |
cutPoint = Math.round(text.length / 2) | |
text = text.slice(0, cutPoint) + text.slice(cutPoint + 1, text.length); | |
// console.log('cropping', textWidth, text); | |
sliceIfNotFitting(); | |
} else { | |
// console.log('now it is good', text, textWidth) | |
if (cutPoint < text.length) { | |
// now add ellipsis we should all be good now | |
input.value = text.slice(0, cutPoint) + '...' + text.slice(cutPoint, text.length); | |
} | |
} | |
} | |
/** | |
* uses canvas to measure given text width with given font styles | |
* http://jsfiddle.net/eNzjZ/34/ | |
**/ | |
function getTextWidth(text, font) { | |
// re-use canvas object for better performance | |
var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas")); | |
var context = canvas.getContext("2d"); | |
context.font = font; | |
var metrics = context.measureText(text); | |
return metrics.width; | |
} | |
sliceIfNotFitting(); | |
} | |
// you can change the input width from the css | |
cropMiddle(document.querySelector('.target'), 'Some very long running text which need cropping now') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment