Learn Create Your Own Split Screen

Next Page

Scratch has the "letter of" block:

In Javascript, to access a particular letter of a string, just use square brackets.

var name="Mary"; var letter = name[2] // letter will contain "r";

The only catch is the first letter of the string is number zero !

This is a bit confusing at first, but very common with computer languages. Consider a variable called "animal" which contains the string "CAT".

Expression Result
animal "CAT"          
animal.length           3
animal [0] "C"
animal [1] "A"
animal [2] "T"

It's worth noting that for every string, the last character is at position "length-1".


Try some experiments - what happens if you try to access a character outside of the valid range, such as beyond its "length-1", or a negative value?