Automatically shorten link urls to a specific length with shortlinks.js

The problem with long urls in text

From time to time, we need to display links as plain URLs in a text. The problem with URLs is that per definition they don't contain spaces (yes, sloppy developers or maintainers use spaces in filenames and risk broken links, but nobody should). No spaces in long words in HTML means that the text does not break into several lines when there is not enough space. This can seriously wreck a layout. Furthermore, long URLs don't look nice and stop the flow when reading a text.

How shortlinks.js can help

shortlinks is a small JavaScript that checks each of the links in the document for long URLs as their text and shortens them to a predefined length.

To use shortlinks, simply add it to the head of your HTML document:

<script type="text/javascript" src="shortlinks.js"></script>

This page uses shortlinks and the following links got shortened by it. Their real length is shown in parenthesis:

More information about starting scripts when the page loads:
http://www.onlinetools.org/articles/unobtrusivejavascript/chapter4.html (http://www.onlinetools.org/articles/unobtrusivejavascript/chapter4.html)
Taming the select element:
http://www.icant.co.uk/forreview/tamingselect/ (http://www.icant.co.uk/forreview/tamingselect/)
A wonderful book on standards based web development:
http://www.amazon.co.uk/exec/obidos/ASIN/1590593812/icantcouk09-21/026-3984440-6639610 (http://www.amazon.co.uk/exec/obidos/ASIN/1590593812/icantcouk09-21/026-3984440-6639610/)

shortlinks comes with its own onload call, if you want to use it together with other scripts, you need to remove the window.onload=shortlinks; section and call the function shortlinks() when you load the page.

Customising shortlinks

There are several variables in the script that define its functionality and the final results:

var mode='middle';
var mustlength=30; 
var connector='...';
var titleadd=' (Full address: %url%)';
var contentlinks=document.getElementsByTagName('a');
mode
defines if the link should be shortened at the right or in the middle.
mustlength
defines the number of letters displayed for each link.
connector
is the string added to the link where it was shortened.
titleadd
is the string added to the title of the link, %url% will be replaced by the real url.
contentlinks
is the array of links that get shortened.

Terms of Use

shortlinks is provided as-is and the developer does not take any liability for any damage caused by it.

The use of the script is free, reselling is prohibited.

Download shortlinks

Discuss shortlinks