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.
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).
var string = "Something Else";var string = new String("Something Else");A string has one basic operator: +
. The plus sign concatenates (in other words, joins together) two strings. Permit me to demonstrate:
var word_1 = "Something";var word_2 = "else";document.getElementById("JS").firstChild.data = word_1 + word_2;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:
var word_1 = "Something";var word_2 = "else";document.getElementById("JS").firstChild.data = word_1 + " " + word_2;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:
var word_1 = "Something";var word_2 = "else";document.getElementById("JS").firstChild.data = word_2 + " " + word_1;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:
var foo = "Something else";" again";document.getElementById("JS").firstChild.data = foo;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.
var foo = "Something else";" again";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.
All strings have substrings, which are merely parts of their text. There are three different methods that will give you substrings.
splitUsage: 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:
split Methodvar string = "The text string we are working with.";var split_strings = [split(" "), // Split on the spaces.split(" ", 4), // Split on the spaces, but has a limit of 4.split(""), // Split into individual characterssplit("", 2), // Split into individual characters, but has a limit of 2split("e"), // Split on the letter "e"split("e", 3) // Split on the letter "e", but has a limit of 3.var trs = document.getElementsByTagName("tbody")[0].getElementsByTagName("tr");getElementsByTagName("td")[1].firstChild.data = split_strings[0].length;getElementsByTagName("td")[2].firstChild.data = split_strings[0][0];getElementsByTagName("td")[3].firstChild.data = split_strings[0][1];getElementsByTagName("td")[4].firstChild.data = split_strings[0][2];getElementsByTagName("td")[5].firstChild.data = split_strings[0][3];getElementsByTagName("td")[6].firstChild.data = split_strings[0][4];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).
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.
substrUsage: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:
substr Methodvar string = "Something else";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.document.getElementById("Str1").firstChild.data = altstr1;document.getElementById("Str2").firstChild.data = altstr2;document.getElementById("Str3").firstChild.data = altstr3;document.getElementById("OStr").firstChild.data = string;substring & slicesubstring(begin, finish);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:
substring and slicevar string = "Something else";var altstr1a = string.substring(0); // Start at index=0 (beginning), go to endvar 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);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;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.
toLowerCase()toUpperCase()These methods return string with a changed case; which case is stated in the method name.
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;You may also search for characters and substrings within strings.
indexOf, lastIndexOf, & searchindexOf(look_for, start_at)lastIndexOf(look_for, start_at)search(look_for)These three methods search for a substring within a string and return the numerical index of where the substring is found. The variable look_for holds the value of the substring to look for, start_at is an optional numerical variable that says where in the string to start looking.
These methods, however, have some important differences: indexOf and search both start at the beginning of the string, while lastIndexOf starts at the end. The variable look_for sets the starting distance from the beginning for indexOf and lastIndexOf, and both will start looking from there—indexOf going forwards and lastIndexOf going backwards—but using that variable with search will cause an error.
In all instances, though, the index of the substring is given in regards to the beginning of the string. 0 is the start of the string, and the index goes up by 1 for each character. A returned value of -1 means that the substring was simply not found in the string.
var string = "If two values are shown between parentheses, the second is not used in the search() method";var indices = [indexOf("e"), string.lastIndexOf("e"), string.search("e")],indexOf("e", 20), string.lastIndexOf("e", 20), string.search("e")],indexOf(","), string.lastIndexOf(","), string.search(",")],indexOf(",", 20), string.lastIndexOf(",", 20), string.search(",")],indexOf("search"), string.lastIndexOf("search"), string.search("search")],indexOf("z"), string.lastIndexOf("z"), string.search("z")]var trs = document.getElementsByTagName("tbody")[0].getElementsByTagName("tr");getElementsByTagName("td")[1].firstChild.data = indices[0][0];getElementsByTagName("td")[2].firstChild.data = indices[0][1];getElementsByTagName("td")[3].firstChild.data = indices[0][2];getElementsByTagName("td")[1].firstChild.data = indices[1][0];getElementsByTagName("td")[2].firstChild.data = indices[1][1];getElementsByTagName("td")[3].firstChild.data = indices[1][2];document.getElementById("JS").firstChild.data = string;matchUsage: foo = string.match(look_for);
This method returns the value look_for if that value is found in the string. If it isn't, the method returns null.
match Methodvar string = "Something else";var match1 = string.match("else");var match2 = string.match("z");document.getElementById("match1").firstChild.data = match1;document.getElementById("match2").firstChild.data = match2;document.getElementById("origin").firstChild.data = string;The reason the result for z
is blank is the script returned null, which appears as a blank.
replaceUsage: foo = string.replace(old_substr, new_substr);
This returns an altered string. It seeks out the first instance of old_substr and replaces it with an instance of new_substr.
var string = "Something else";var replace1 = string.replace("else", "new");var replace2 = string.replace("z", "new");document.getElementById("replace1").firstChild.data = replace1;document.getElementById("replace2").firstChild.data = replace2;document.getElementById("origin").firstChild.data = string;Note that I said the first instance. If you want to replace them all, it gets a bit more complex. I'll explain how to do it in Regular Expressions.
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:
Just like other arrays, the index starts at 0
.
The method toString will return a value as a string. For example, look at the following code:
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.
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:
pre element or an alert box).π in the various client-side languages:
ufollowed by hexadecimal digits. If you have more, you will get a character—but it will followed by the
extrahexadecimal digits, and the character may not be the one you want.
π is out of the question, as it requires at least 3 hexadecimal digits.#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:
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.
Knowing about this is very important, especially if you wish to write a script that reads said text.