Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using JQuery Linkify plugin, how do I truncate the url?

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?

like image 297
TIMEX Avatar asked Feb 06 '12 06:02

TIMEX


2 Answers

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.

like image 99
antyrat Avatar answered Nov 16 '22 03:11

antyrat


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.

like image 20
Thomas Nadin Avatar answered Nov 16 '22 03:11

Thomas Nadin