Text

JavaScript works a lot with text. Earlier, I mentioned that foo could hold the value Something else. In the context of JavaScript, Something else is called a string, which basically means a piece of text, as I said back in CSS-Generated Content.

The most important thing to remember is that strings must always be in quotation marks. Otherwise the browser will think that your text is a variable (such as foo), or a node (such as document), or a number, or two variables (if you don't put Something else in quotaton marks, the browser will think that Something and else are both variables) and you'll probably end up with errors.

Creating Strings

There are two ways of creating strings. The simplest way is to simply place some text into quotes and assign it to a variable. The other is to create the string as an object and assign that to a variable (though I'm not sure of the advantage).

Creating A String
Assigning The String To A Variable
var string = "Something Else";
Assigning A String Object To A Variable
var string = new String("Something Else");

Concatenating Strings

A string has one basic operator: +. The plus sign concatenates (in other words, joins together) two strings. Permit me to demonstrate:

Concatenating A String
var word_1 = "Something";
var word_2 = "else";
document.getElementById("JS").firstChild.data = word_1 + word_2;
A string concatenated.  A space seems to be missing.

You may be wondering, Where'd the space go? Well, if you look closely at the code, the space simply isn't there. word_1 doesn't have it, neither does word_2, and it was not added in at any time. This is important, JavaScript doesn't care about what results it spits out, it's just following orders. So let's add in a space:

Concatenating A String And Adding A Space
var word_1 = "Something";
var word_2 = "else";
document.getElementById("JS").firstChild.data = word_1 + " " + word_2;
String fix

Yes you can use more than one operator in an equation. And now the value of foo is Something else.

But do remember that the order that the strings are placed in are important. In the example below, I will switch word_1 and word_2 when concatenating them:

Reversing The Variables
var word_1 = "Something";
var word_2 = "else";
document.getElementById("JS").firstChild.data = word_2 + " " + word_1;
String reversal

Adding Text To A String

Concatenation allows you to adjust the text value of a variable. For example, if foo holds the value Something else, and you want to add the text again, it's really easy to do:

Adding Text To A String
var foo = "Something else";
foo = foo + " again";
document.getElementById("JS").firstChild.data = foo;
String Addition

Concatenation Shorthand

The short-hand expression for adding text uses a combination of the + and = operators: +=. This operator tells the script that the following text is to be added to the text already contained in the variable. This text will always come after, not before.

Adding Text To The End Of A String
var foo = "Something else";
foo += " again";

String Methods

Methods for strings are much like methods for arrays: these methods are part and parcel of every string variable. The string variable I'll use for these will be string. All these methods return a value, but the original value of string is left unchanged—unless, of course, you assign the changed string to string.

Substring Methods

All strings have substrings, which are merely parts of their text. There are three different methods that will give you substrings.

split

Usage: foo = string.split(divider, piece_count);

This method breaks up a string and returns the pieces in an array. The variable divider is the substring used to make the division. For example, divider = " " will cause spaces to be the divider, and the string will become an array of words. If divider = "", then the array will consist of the individual characters. The variable piece_count is optional, and limits how many pieces are actually in the array. If it is specified, the excess is discarded.

Below is an example of this kind of splitting:

Using the split Method
// Create String
var string = "The text string we are working with.";
 
// Create array of arrays. Each array is our string split in a different fashion.
var split_strings = [
string.split(" "), // Split on the spaces.
string.split(" ", 4), // Split on the spaces, but has a limit of 4.
string.split(""), // Split into individual characters
string.split("", 2), // Split into individual characters, but has a limit of 2
string.split("e"), // Split on the letter "e"
string.split("e", 3) // Split on the letter "e", but has a limit of 3.
];
 
// Write the strings.
var trs = document.getElementsByTagName("tbody")[0].getElementsByTagName("tr");
trs[0].getElementsByTagName("td")[1].firstChild.data = split_strings[0].length;
trs[0].getElementsByTagName("td")[2].firstChild.data = split_strings[0][0];
trs[0].getElementsByTagName("td")[3].firstChild.data = split_strings[0][1];
trs[0].getElementsByTagName("td")[4].firstChild.data = split_strings[0][2];
trs[0].getElementsByTagName("td")[5].firstChild.data = split_strings[0][3];
trs[0].getElementsByTagName("td")[6].firstChild.data = split_strings[0][4];
Author's Note: The above six lines repeat five more times, with 36 such lines total. Both the index of trs and the first index of split_strings increase by 1 each time. For the sake of space, I omitted the rest of the lines from this example.
document.getElementById("OStr").firstChild.data = string;

In the table below, row numbering and column numbering both start at 0, going from top to bottom (rows) and left to right (columns).

String splitting

If a table cell is blank, that's because its value is a space. If a table cell contains the word undefined, that's because its respective array element doesn't exist, which is the meaning of undefined. Note that, although string was written to its respective node last and after being used in several methods, it is unchanged.

substr

Usage:foo = string.substr(begin, length);

This method returns a portion of a string. begin contains a numeric value that tells where in the string to begin (the beginning of the string is 0). The optional variable length is a numerical value that states how long a string you want. Without it, this method extracts to the end of the string.

Below is an example:

Using The substr Method
// Create String
var string = "Something else";
 
// Assign various substrings
var altstr1 = string.substr(0); // Start at index = 0 (beginning), go to end.
var altstr2 = string.substr(3); // Start at index = 3, go to end.
var altstr3 = string.substr(1, 4); // Start at index = 1, extract 4 characters.
 
// Write to the dd elements with the following IDs:
document.getElementById("Str1").firstChild.data = altstr1;
document.getElementById("Str2").firstChild.data = altstr2;
document.getElementById("Str3").firstChild.data = altstr3;
document.getElementById("OStr").firstChild.data = string;
Substrings

substring & slice

  • Usages:
  • foo = string.substring(begin, finish);
  • foo = string.slice(begin, finish);

These methods works almost exactly like substr, except the optional second variable tells you where in the string to end (again, stated by a numerical value), rather than the length of the substring.

The only difference between these two methods is that substring extracts the characters and puts them in a new string, while slice just extracts an actual string. This makes little difference except in one instance, shown below:

Using substring and slice
// Create String
var string = "Something else";
 
// Assign various substrings
var altstr1a = string.substring(0); // Start at index=0 (beginning), go to end
var altstr1b = string.slice(0);
var altstr2a = string.substring(3); // Start at index=3, go to end.
var altstr2b = string.slice(3);
var altstr3a = string.substring(5, 7); // Start at index = 5, go to index = 7.
var altstr3b = string.slice(5, 7);
var altstr4a = string.substring(6, 1); // Start at index = 6, go to index = 1.
var altstr4b = string.slice(6, 1);
 
// Write to the td elements with the following IDs:
document.getElementById("Str1a").firstChild.data = altstr1a;
document.getElementById("Str1b").firstChild.data = altstr1b;
document.getElementById("Str2a").firstChild.data = altstr2a;
document.getElementById("Str2b").firstChild.data = altstr2b;
document.getElementById("Str3a").firstChild.data = altstr3a;
document.getElementById("Str3b").firstChild.data = altstr3b;
document.getElementById("Str4a").firstChild.data = altstr4a;
document.getElementById("Str4b").firstChild.data = altstr4b;
document.getElementById("OStr").firstChild.data = string;
Substrings

As you can see, substring returns the characters between index 6 and 1, but slice doesn't return anything. This is the only difference I've found.

Case Methods

These methods return string with a changed case; which case is stated in the method name.

Changing Case
var string = "Something else";
var upper = string.toUpperCase();
var lower = string.toLowerCase();
document.getElementById("Upper").firstChild.data = upper;
document.getElementById("Lower").firstChild.data = lower;
document.getElementById("Orgnl").firstChild.data = string;
Upper and Lower Cases.

Strings As Arrays

String objects can also act as arrays. The length property returns the number of characters in the value of string, while an array index would refer to a single character in that string. For example, if string held the value String, then the values of each array element would be:

  1. S
  2. t
  3. r
  4. i
  5. n
  6. g

Just like other arrays, the index starts at 0.

Converting a value to a string

The method toString will return a value as a string. For example, look at the following code:

Converting the Value of foo To A String
string = foo.toString;

string will contain whatever foo contains converted to a string, whether it be a number, a boolean value, an array (the values will be seperated by commas), etcetera. This will not work with a null value, since null means there is nothing to convert.

Special Characters

JavaScript has a way of creating special characters. This can include entity references as explained in Special Characters and CSS-Generated Content.

Special characters are preceded by a backslash (\), also known as the escape character. Some special characters have a specific meaning. Here's a list of some of them:

\n
Creates a new line (best used in a pre element or an alert box).
\r
Carriage Return (the name comes from older technology; it means that the cursor returns to the start of the line.)
\t
Tab character
\u
This precedes a four-digit hexadecimal numeric character reference. Let me compare the various ways of showing the Greek letter π in the various client-side languages:
(X)HTML
π
CSS
\0003C0
JavaScript
\u03C0
Unlike the other examples, in JavaScript, you must have exactly four hexadecimal digits. If you have fewer, all that will show up is a u followed by hexadecimal digits. If you have more, you will get a character—but it will followed by the extra hexadecimal digits, and the character may not be the one you want.
\x
This precedes a two-digit hexadecimal numeric character reference, which restricts it to ASCII characters, which I mentioned in Special Characters. Yes, that means the Greek letter π is out of the question, as it requires at least 3 hexadecimal digits.
\###
Here, # stands for any digit from 0 to 7. This is an octal code, a Base 8 numbering system I mentioned back in Tables when I was demonstrating that structure. These codes have a range of 418 to 3778 (33 - 255 in decimal, 2116-FF16 in hexadecimal). Since 3C016 in hexadecimal is 17008 in octal, π cannot be represented in Base 8—so far as JavaScript is concerned.

The backslash also allows some special characters to be interpreted literally. Below are some examples:

\\
This will cause a literal backslash to appear.
\"
This will cause a literal quotation mark to appear.

A Note On New Lines

When I described the pre element back in Block Elements, I showed that creating a new line in that element would cause text that appeared before to appear on one line and the text after to appear on the next. Various browsers will interpret that new line in two different ways when the text of that element is read by JavaScript.

\n
As a new line.
\r\n
As a carriage return, then a new line.

Knowing about this is very important, especially if you wish to write a script that reads said text.