Category Archives: Javascript

Javascript

Javascript: Extract a specific character in a string

Came across this today and really liked it as a quick tip.

If you want to extract the ‘n-th’ character from a string in Javascript, you can do this:-

"MATTHEW"[n-1];

So, if you wanted to pull out the 4th character, you would do this:-

"MATTHEW"[3];

The reason for subtracting one is that Javascript arrays are zero-based – that is, they start at zero rather than one.

You could also do the same with a variable:-

var string = "MATTHEW";
alert(string[3]); //returns the second 'T'

Javascript

Javascript quick tip – returning urls

A few quick Javascript tips for you.  If you want to return or store the value of the current url of your page, try this:-

window.location.href

This will give you the entire url that is displayed in the address bar.

 

If you have a url containing a hash value (ie http://www.2toria.com/index.php#section1) and want to return the hash, then use this:-

window.location.hash

 

Want just the top-level domain name (eg www.2toria.com)?  Give this a whirl:-

window.location.hostname