PC Nerding

The cheapest JS URL shortener ever

After my previous article about shortening urls using htaccess, today I’m posting a little JS snippet that will allow to shorten urls, using a JSON array to store shorter and longer urls. The script will look in url parameters for a short url and redirect to the associated longer url. Have a look:

<!-- // Function declaration
function shorturl_redirect() {
	// This JSON array contains all the shorturl/url pairs
	var urls =[	{ "shorturl":"?lndm" , "redirect":"" },
			{ "shorturl":"?example" , "redirect":"" },
			{ "shorturl":"?twitter" , "redirect":"" },
	// Get the url parameter
	var shorturl =;
	// If there's no url parameter stop script execution
	if(!shorturl || 0 === shorturl.length) { return; }
	// Now the function will look though urls array and if a valid shorturl is found it will redirect the browser to the longer url
	for(i = 0; i < urls.length; i++) {
		if(shorturl == urls[i].shorturl) {
// Function call
// -->

Now for an example, if you point your links to or the script redirect your browser to this site homepage.

Some quick notes:
- It will work on any hosting/subdirectory/webpage/cms/browser combination, unless the visitor is actively blocking JavaScript (eg. NoScript plugin on Firefox). All php cms still need to be fully loaded by the hosting environment before serving the script.
- I suggest placing this snippet (or .js file) between head tags, ideally you want the browser to stop loading html and go to the provided link.
- You can wrap the code into a JS anonymous function, since the code needs to be executed only once.
- The script is really small in size: the above example is only 834 bytes including comments. Byte size will vary according to your array size and url lenghts, for example I made an array with 50 entries and it was 5,3kb.
- It does not require additional libraries, eg. jQuery, or additional url shortening services, eg. or Yourls.
- Depending on the behavior you may want, you could change window.location.replace with window.location.href . For more information read here.

By Andrea Giorgio "Muu?" Cerioli

Italian developer, designer, maker who loves everything in technology: mechanics, electronics, IT, 3D printing.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.