Strings & Arrays in JavaScript


Create a string

str = "This is a string";
str = new String ("This is a string");

Concatenation - adding one string to another

str = str + " test";
str += ".";

Various string methods

string.length;
string.toUpperCase ();
string.toLowerCase ();

... if string = "ABCDEDGHIJKLMNOPQRSTUVWXYZ ABCD" ...

string.substring (0, 4) = "ABCD"
string.charAt (0) = "A"
string.charAt (25) = "Z"
string.indexOf ("EFGH") = 4
string.lastIndexOf () = 25
string.lastIndexOf ("ABCD") = 27

Arrays

Arrays can contain numeric values of strings. Unlike most other JavaScript variables, an array must be declared before it is used.

scores = new Array(30);
	
scores[0] = 25;
scores[1] = 35;
scores[2] = 105;
scores[3] = 215;

names = new Array(10);
	
names[0] = "Laura Jean Baum";
names[1] = "Laura Powell";

names[0].substring (6, 9) = "Jean"

Splitting & Joining a string

parts = names[0].split (" ");
	
parts[0] = "Laura"
parts[1] = "Jean"
parts[2] = "Baum"

parts.join (" ") = "Laura Jean Baum"

sortedNames = parts.sort ();

sortedNames[0] = "Baum"
sortedNames[1] = "Jean"
sortedNames[2] = "Laura"