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":"http://www.lanoiadimuu.it" },
			{ "shorturl":"?example" , "redirect":"http://www.example.com" },
			{ "shorturl":"?twitter" , "redirect":"http://twitter.com/lanoiadimuu" },
	// Get the url parameter
	var shorturl = location.search;
	// 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) {
			window.location.replace(urls[i].redirect)
			break;
		}
	 }
}
// Function call
shorturl_redirect();
// -->

Now for an example, if you point your links to www.yourexample.com/?lndm or www.yourexample.com/index.html?lndm 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. Bit.ly or Yourls.
- Depending on the behavior you may want, you could change window.location.replace with window.location.href . For more information read here.

About Andrea Giorgio "Muu?" Cerioli

Italian developer who loves everything in technology, from mechanics to electronics to IT. A guy who actually messed up with his school education and dropped it at 17, pursuing his own interests only.

Leave a Reply

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