JavaScript Strings

It is tempting to think of strings as arrays. They have a length property and you can access individual elements with a numberical index. You can split a string into an array and join an array back into a string. Strings are not arrays, however, and there are some very distinct differences in what you can do with them.

Strings are sets of characters, they might include letters, numbers, punctuation, and whitespace. While you can access individual characters from string by numerical index, you shouldn't because it's read-only. Use charAt instead.

var s = 'the sky is blue';  
s[2] // 'e'  
s[2] = 'f'; // 'e'

s.charAt(2); // 'e'  

You are unable to change individual characters in a string because strings are immutable. They cannot be edited, they can only be replaced. To add parts to a string, you have to add it to itself. You can do this with arithmetic or with concat. You must assign it to itself or to a new value or it won't save.

var s = 'the sky is blue', g = 'the grass is green';

var sg = s + ' ' g;       // don't forget the space!  
var s += ' ' + g;  
var s = s.concat(' ',g);     // => all return 'the sky is blue the grass is green'  

To remove parts of a string, you can cut them off and save the remainder to a new variable or to itself. The methods for shortening strings are slice and substring. They both accept two parameters, starting index (inclusive, 0 for beginning) and ending (exclusive, length for end of string). Slice can also accept negative values for start and end, and will start the index from the end of the string.

The last kind of method I want to talk about is the search methods. There are two for strings: indexOf and search. indexOf returns the index at which a string begins or -1 if it is not found. Search can also take regular expressions. You can also replace values with replace using regex.

More information on regex with string methods can be found here.