Tag Archives: array

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'