JSFiddle - React, Tailwind, and code Playground
by David Thomas
HTML
<ul>
<li class="midEllipsis">abcdefghijklm</li>
</ul>
JavaScript
function centralEllipsis(opts) {
var settings = {
'maxLength': 7,
'ellipsis': '…',
'writeToAttribute': 'data-originaltext'
},
_this = this;
for (var prop in opts) {
if (opts.hasOwnProperty(prop)) {
settings[prop] = 'undefined' !== typeof opts[prop] ? opts[prop] : settings[prop];
}
}
var prefixLength = Math.ceil(settings.maxLength / 2),
suffixLength = settings.maxLength - prefixLength,
originalText = _this.title = _this.textContent,
prefix, suffix;
if (settings.maxLength < originalText.length) {
_this.setAttribute(settings.writeToAttribute, originalText);
prefix = originalText.substr(0, prefixLength);
suffix = settings.maxLength < 2 ? '' : originalText.substr(-suffixLength);
_this.innerHTML = prefix + settings.ellipsis + suffix;
}
}
Array.prototype.forEach.call(document.querySelectorAll('.midEllipsis'), function (el) {
centralEllipsis.apply(el, [{}]);
});