https://github.com/maranomynet/linkify
I'm using this plugin. It works, and everything's fine. But is there an option I can plug into it so that if the url length is longer than "X", then truncate it, and add "..."?
Right now the URLs are so long.
I notice in the demo there is a "handleLinks" callback function, but how do I use that?
You're right, you can use handleLinks
callback function. For example I wrote simple functional that you need:
handleLinks: function (links) {
for (var i = 0, cnt = links.length, tmpLink; i < cnt; i++) {
tmpLink = links[i].innerHTML;
if (tmpLink.length > 10) {
links[i].innerHTML = tmpLink.substr(0, 10) + '...';
}
}
}
It truncates links if they longer than 10 characters. You can modify this script by your needs.
For URL truncating I choose to shorten in the middle, as the domain and file are usually more important than the directory path.
Taken and adapted for this question from my GitHub fork of Andrew Plummer's JavaScript Library 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;
}
Example of shortening a Url so the resultant string is 20 characters long:
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'
Note: this code has only been proof read and not unit tested. The Sugar implementation has been unit tested, however.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With