Blake O'Hare .com

JavaScript Tutorial, Part 4 - Strings

So far in all the examples, everything has dealt with numbers and math. One of the other primary data types in JavaScript are strings.

Strings are just pieces of text.

var greeting = "Hello";

You can join strings together, just like adding numbers...

var greeting = "Hello";
greeting = greeting + ", World!";


As for getting a subsection of a string, there are a few ways to do that:

Slice is a function that exists on each string that will extract all characters from a given starting point and up to (but not including) some end point. These are called indices (plural of index) and they count starting from 0.
var text = "abcdefg";
var newtext = text.slice(3, 5);


A similar function to slice is substr which stands for "Sub-string". The only difference is the 2nd number you pass in to .substr is the number of characters you want starting from the first index, as opposed to specifying an end index.

var text = "abcdefg";
var newtext = text.substr(3, 2);

This code does the same things as the previous code snippet and yields "de".

With both slice and substr, you can omit the 2nd number and they will both return the string starting from the first index and going all the way to the end.

If you only want 1 character at a given index, then its more efficient to just use a function called charAt.

var text = "abcdefg";
var char = text.charAt(2);


There's also another way, but I won't get in to that until we talk about lists.

It's also important to note that all of these functions do NOT modify the original string. They return copies. There is no way to modify a string once it has been created. This is true of most modern languages.

Lastly, it's useful to know how many characters are in a string. There is a property on every string called length which simply returns the number of characters in a string.

var text = "abcdefghijklmnopqrstuvwxyz";


length is a property, not a function. That means don't put parenthesis after it.
This is WRONG.


These are only a couple of the built-in string methods. But these are the probably the most common/useful.