Strings



index
Disabled back button Next Section
printable version

Section 1: Introduction

A string is sequence of Unicode characters, like 'JavaScript', 'Hello world!', 'http://cob.isu.edu' or even '2220'. Strings are normally used to represent text.

What can we do with strings?

When you write JavaScripts, you need to know what strings are and how they work.


Quotes

When you declare and manipulate string literals in JavaScript, always enclose them in matching single quotes ' or double quotes ".

Here are two example strings:

var string1 = 'Hello world!';

var string2 = 'I am a JavaScript wizard.';

Now we have declared two variables, string1 and string2, and put strings in them.

If you create a string with nothing in it, it is called an empty string. It is normally created by two quote marks with nothing between them: "".

Escape Sequences

Some characters that you may want in a string may not exist on the keyboard, or may be special characters that can't appear as themselves in a string.

For example, there is a problem with the following statement:

var string2 = 'I'm a JavaScript wizard.';

The string is enclosed in single quotes, but has a single quote in it, so JavaScript thinks that the string ended when it encountered the embedded single quote, doesn't understand what comes next, and gives error messages.

So, you need to escape the single quote, telling the browser to treat the quote as a character, and not as a command to end the string.

This is done by placing a backslash \ before it:

var string2 = 'I\'m a JavaScript wizard.';

Note that you can put double quotes in the string without escaping them, since you've defined the single quotes as the beginning and end of the string, so

var string2 = 'I\'m a JavaScript "wizard".';

or

var string9 = 'The librarian shouted "Quiet" quite loudly.';

gives no problems.

The double quotes are automatically treated as parts of the string, not as commands.

Some escape characters are as follows:

Escape Sequence Character
\b Backspace
\t Tab. Tabs behave erratically on the Web and are best avoided, but sometimes you need them.
\v Vertical tab
\f Formfeed
\n New line (\u0000a). Inserts a line break at the point specified. It is a combination of the carriage return (\r) and the form feed (\f).
\r Carriage return
\" Double quote
\' Single quote, or an apostrophe, such as in can\'t.
\\ The backslash, since by itself it is a command.
\x99 A two digit number specifying the hexadecimal value of a character in the Latin-1 character set (ASCII).
\u9999 A four digit hexadecimal number specifying a character in the Unicode character set. This is not supported before JavaScript 1.3.
Section 2: Length

The only string property that we will discuss is .length, which returns the number of characters in a string.

So if you want to get the length of 'Hello world!' you can write:

var strLength = 'Hello world!'.length;

But earlier we assigned this string literal to variable string1, which made string1 a string, so it also has a length and the following yields the same result:

var strLength = string1.length;

Another example:

var string2 = 'I am a JavaScript wizard.';

alert(string2.length);

returns 25.

Note that the length is 1 more than the index number of the last character (since indexes start counting at 0, as we'll see later).

Note that I often use alert in the examples.)

Section 3: Finding Something in a String: indexOf()

One of the most widely used built-in methods is indexOf.

Each character in a string is associated with an index number that indicates its position in the string. So the index of 'w' in string string1 is 6.

Adding .indexOf('') behind the string name and putting the character you're looking for between the quotes will reveal where it appears in the string. Thus,

var string1 = 'Hello world!';

alert(string1.indexOf('w'));

gives 6.

If the same character occurs more than once, this method gives the first occurrence only. So

string1.indexOf('o')

gives 4 because that's the index of the first 'o' in the string. 

You can also look for a combination of characters, or a substring, inside a string.

indexOf returns the position of the first character of the substring. So

alert(string1.indexOf('o w'));

also gives 4 because that's the index of the 'o'.

Furthermore it's possible to search for a character beginning at any point in a string.

For instance, the statement

alert(string1.indexOf('o',5));

returns the index number of the first 'o' in the string after index 5, so it would return 7.

Finally, if the character or combination is not present in the string, indexOf returns -1.


lastIndexOf

There's also lastIndexOf that returns the last occurrence of the character or combination. It otherwise works exactly as indexOf. Thus

var string2 = 'I am a JavaScript wizard.'

alert(string2.lastIndexOf('a'));

returns 21 because that's the index of the last 'a' in the string.


Additional substring location functions (Reference) Expand topic.

Section 4: Copying Portions of a String: substring()

substring() is used to take a portion of a string, or a substring.

So for instance

var string1 = 'Hello world!';

alert(string1.substring(4,8));

returns 'o wo', from the first 'o' (index 4) to the second one (index 7).

The second argument is optional, but if you omit it then the function will extract to the end of the string.

For instance, you can write

var string1 = 'Hello world!';

alert(string1.substring(4));

This returns the substring beginning with the character at index 4 on, or 'o world!'.


Additional substring extraction functions (Reference) Expand topic.

Section 5: Replacing Portions of a String: replace()

The replace() method is used to replace some characters with some other characters in a string.

The syntax is replace(findstring,newstring), in which both arguments are required.

var string2 = 'I am a JavaScript wizard.'

alert(string2.replace('wizard','newbie')); // produces 'I am a JavaScript newbie.'

Section 6: Comparing strings

In JavaScript, you use the less-than and greater-than operators to compare strings:

var strA = "a";

var strB = "b";

if (strA < strB) // true because 97 is less than 98 (Unicode)

     alert(strA + " is less than " + strB);

else if (strA > strB)

     alert(strA + " is greater than " + strB);

else

     alert(strA + " and " + strB + " are equal.");

Section 7: String Concatenation

An analogy for string concatenation is coupling rail cars (video).

Strings an be concatenated using the overloaded plus (_) operator.

var newString0 = string1 + string2;

results in

Hello world!I am a JavaScript wizard.

But of course you want a space between the two sentences. No problem. By writing

var newString1 = string1 + ' ' + string2;

we concatenate three strings: string1, ' ' (one space) and string2 and we get

Hello world! I am a JavaScript wizard.


You can even use numbers or calculations, like:

var newString2 = string1 + 3 * 3 + string2;

Now we concatenate string string1, then the result of 3*3, treated as a string for the occasion, and then string2, which gives

Hello world!9I am a JavaScript wizard.


Watch out if you want to add numbers. This

var newString3 = string1 + 3+3 + string2;

concatenates four strings: string1, 3, 3 and string2, because + in this context means concatenate strings, not add, and gives

Hello world!33I am a JavaScript wizard.

Use parentheses if you want to add 3 and 3 before making the string.

var newString4 = string1 + (3+3) + string2;

concatenates string1, the result of 3+3 and string2 and gives

Hello world!6I am a JavaScript wizard.


Strings can also be concatenated using the concat function.

var string10 = "blue";

var string11 = "berry";

var string12 = string10.concat(string11);

Section 8: Strings and numbers

Refer to data types notes.

Section 9: Miscellaneous string functions

Miscellaneous string manipulation expand


split

split () is a specialized method that you sometimes need.

split() allows you to split a string at a certain character.

You must put the result in an array, not in a simple variable.

Let's split string2 on the spaces.

var string2 = 'I am a JavaScript wizard.'

var temp = new Array();

temp = string2.split(' ');

Now the string has been split into 5 strings that are placed in the array 'temp'. The spaces themselves are gone.

temp[0] = 'I';

temp[1] = 'am';

temp[2] = 'a';

temp[3] = 'JavaScript';

temp[4] = 'wizard.';


toLowerCase and toUpperCase

Finally two methods that you sometimes need:

var string2 = 'I am a JavaScript wizard.'

var string3 = string2.toUpperCase()

returns 'I AM A JAVASCRIPT WIZARD.'.

Character manipulation (Reference) Expand topic.

Extra (almost useless) string functions (Reference) Expand topic.

Section 10: Resources

MDN Strings

Complete reference

JavaScript - The Strings Object

JavaScript String Methods You Probably Haven’t Heard Of