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: (
Taming the select element: (
A wonderful book on standards based web development: (

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');
defines if the link should be shortened at the right or in the middle.
defines the number of letters displayed for each link.
is the string added to the link where it was shortened.
is the string added to the title of the link, %url% will be replaced by the real url.
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