W przypadku obcinania adresów URL wybieram skrócenie w środku, ponieważ domena i plik są zazwyczaj ważniejsze niż ścieżka do katalogu.
Zrobione i dostosowane do tego pytania z mojej GitHub fork Biblioteki JavaScript Andrew Plummer Sugar.
String.prototype.shorten = function(length, position, countSplitter, splitter) {
if (this.length < 1 && length < 1) return String(this);
if (!(typeof(splitter) === 'string')) splitter = '...';
if (!(typeof(countSplitter) === 'boolean')) countSplitter = true;
var balance = (countSplitter) ? splitter.length : 0;
if (length <= balance || this.length <= length) return String(this);
// Perform shortening
var shortened, beforeSplitter, afterSplitter;
if (position == 'left') {
afterSplitter = this.substring(this.length - length + balance, this.length - 1);
shortened = splitter + afterSplitter;
} else if (position == 'right') {
beforeSplitter = this.substring(0, length - balance);
shortened = beforeSplitter + splitter;
} else {
beforeSplitter = this.substring(0, Math.ceil((length/2) - (balance/2)));
afterSplitter = this.substring(this.length - Math.floor((length/2) - (balance/2)), this.length);
shortened = beforeSplitter + splitter + afterSplitter;
}
return shortened;
}
Przykład skracania URL tak powstałego łańcucha wynosi 20 znaków:
var toShorten = 'http://stackoverflow.com/questions/9156458/when-using-jquery-linkify-plugin-how-do-i-truncate-the-url';
var shortened = toShorten.shorten(20); // Output: 'http://st...-the-url'
Uwaga: Ten kod jest tylko do odczytu i nie dowód Urządzenie testowane. Model Sugar implementation został jednak unit tested.
Jeśli przerwiesz link, będzie on bezużyteczny jako link, ale jeśli chcesz go wyświetlić w ten sposób, możesz zaimplementować inną wtyczkę jQuery, aby to zaimplementować. – NAVEED