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";
window.alert(greeting);

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

var greeting = "Hello";
greeting = greeting + ", World!";
window.alert(greeting);

js_tutorial_9.png

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);
window.alert(newtext);

"de"

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);
window.alert(newtext);

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);
window.alert(char);

"c"

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";
window.alert(text.length);

"26"

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

text.length;
Correct.

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