12. Strings


In This Chapter

Understand how text is treated in JavaScript

Learn how to perform common string operations

Look at the various string properties


I have a hunch that you are a human being. As a human, you probably relate really well with words. You speak them. You write them. You also tend to use a lot of them in the things you program. As it turns out, JavaScript likes words a whole lot as well. The letters and funny-looking symbols that make up your (and my) language have a formal name. They are known as strings:

Image

That image may not be very representative of what I am talking about. In fact, that image has nothing to do what I am talking about...

Anyway, strings in JavaScript are nothing more than a series of characters. Despite how boring that sounds, accessing and manipulating these characters is a skill that you must be familiar with. That’s where this chapter comes in.

Onwards!

The Basics

The way you can work with strings is by just using them in your code. Just make sure to enclose them in single or double quotes. Below are some examples:

var text = "this is some text";
var moreText = 'I am in single quotes!';

alert("this is some more text");

Besides just listing strings, you’ll often combine a couple of strings together. You can easily do that by just using the + operator:

var initial = "hello";
alert(initial + " world!");

alert("I can also " + "do this!");

In all of these examples, you are able to see the string. The only reason I point out something this obvious is that, when you can see the contents of your string as literally as you do, these strings are more appropriately known as string literals. That doesn’t change the fact that the resulting structure is still a built-in primitive type called a string (you know...a basic pizza ingredient from the previous chapter).

If you had to visualize what the text and moreText strings look like, they would look as shown in Figure 12.1.

Image

FIGURE 12.1 What our code looks like as visualized by weird lines and colorful boxes!

You just have your two variables pointing to some literal chunks of text. There isn’t anything else that is going on. If you are wondering why I wasted this space in visualizing something so obvious, the visualizations will get more complex once we move into Object territory. You’ll see hints of that in this chapter itself.

Anyway, all of this isn’t particularly important...yet. The only important thing to keep in mind is that you need to wrap your string literals in either quotation marks (") or apostrophes (') to designate them as a region of text. If you don’t do that, bad things happen and your code probably won’t run.

That’s all there is to the basics. The fun stuff comes from using all of the functionality JavaScript provides for working with strings. We’ll look at that and more in the following sections.

String Properties and Methods

When you are working with strings, the underlying String object implementation contains a lot of properties that make working with text (usually) easier. In the following sections, instead of going over every property and boring both of us to death, I’ll just focus on the important ones in the context of tasks you will be doing.

Accessing Individual Characters

While a string looks like one cohesive unit, it is actually made up of a series of characters. You can access each character in several ways. The most common way is by using array/bracket notation and passing in a number that corresponds to the index position of the character:

var vowels = "aeiou";
alert(vowels[2]);

In this example, I will see the i character because it is the item at the second index position. If you have no idea what just happened, Figure 12.2 may help.

Image

FIGURE 12.2 How the index positions map to the string character.

Here is something you should keep in mind when the word index is thrown around. Index positions in JavaScript start at 0 and move up from there. That is why your index position is 2, but the count of the element at that position is actually 3. This gets less weird the more you work with JavaScript and other languages that don’t contain the words Visual and Basic.

To go one step further, you can access all characters in your string by just looping through the index positions. The start of the loop will be 0, and the end of your loop will be determined by the length of your string. The length of your string (aka a count of the number of characters) is returned by the length property.

Here is an example of the preceding paragraph in action:

var vowels = "aeiou";

for (var i = 0; i < vowels.length; i++) {
     alert(vowels[i]);
}

While you may not be looping through a string all the time, it is very common to use the length property to get a count of the number of characters in your string.

If you don’t get along with the array/bracket notation, you also have the charAt method that returns a character at a specified index position:

var vowels = "aeiou";
alert(vowels.charAt(2));

The end result is identical to what you see using the array notation. I wouldn’t really use this method unless you care about really old browsers like Internet Explorer 7. Yep, I didn’t think you did either.

Combining (aka Concatenating) Strings

To combine two strings together, you can just use the + or += operators and just add them like you would a series of numbers:

var stringA = "I am a simple string.";
var stringB = "I am a simple string, too!";

alert(stringA + " " + stringB);

Notice that, in the third line, we add both stringA and stringB together. Between them, we specify an empty space character (" ") to ensure there is a space between each of the individual strings. You can mix and match string literals with string primitives and string objects and still get your text all combined together.

For example, this is all valid:

var textA = "Please";
var textB = new String("stop!");
var combined = textA + " make it " + textB;

alert(combined);

Despite all of the mixing going on, the type of the combined variable is simply a string primitive.

For combining strings, you also have the concat method. You can call this method from any string and specify a sequence of string primitives, literals, and objects that you want to combine into one...megastring:

var foo = "I really";
var blah = "why anybody would";
var blarg = "do this";

var result = foo.concat(" don't know", " ", blah, " ", blarg);


alert(result);

For the most part, just use the + and += approach for combining strings. It is faster than the concat approach. With everything else being equal, who wouldn’t want some extra speed in their code?

Making Substrings out of Strings

Sometimes, what you are interested in is a sequence of characters somewhere in the middle of your string. The two properties that help satisfy this interest are slice and substr. Let’s say we have the following string:

var theBigString = "Pulp Fiction is an awesome movie!";

Let’s mess with this string for a bit.

The slice Method!

The slice method allows you to specify the start and end positions of the part of the string that you want to extract:

var theBigString = "Pulp Fiction is an awesome movie!";
alert(theBigString.slice(5, 12));

In this example, we extract the characters between index positions 5 and 12. The end result is that the word Fiction is what will get returned.

The start and end position values do not have to be positive. If you specify a negative value for the end position, the end position for your string is what is left when you count backwards from the end:

var theBigString = "Pulp Fiction is an awesome movie!";
alert(theBigString.slice(0, -6));

If you specify a negative start position, your start position is the count of whatever you specify starting from the end of the string:

var theBigString = "Pulp Fiction is an awesome movie!";
alert(theBigString.slice(-14, -7));

You just saw three variations of how the slice method can be used. I’ve never used anything but the first version with a positive start and end position, and you’ll probably fall in a similar boat.

The substr Method!

The next approach we will look at for splitting up your string is the substr method. This method takes two arguments as well:

var newString = substr(start, length);

The first argument is a number that specifies your starting position, and the second argument is a number that specifies the length of your substring. This makes more sense when we look at some examples:

var theBigString = "Pulp Fiction is an awesome movie!";

alert(theBigString.substr(0, 4)); // Pulp

We start the substring at the zeroth position and count four characters up. That is why Pulp is returned. If you want to just extract the word Fiction, this is what your code would look like:

var theBigString = "Pulp Fiction is an awesome movie!";

alert(theBigString.substr(5, 7)); // Fiction

If you don’t specify the length, the substring that gets returned is the string that goes from the start position to the end:

var theBigString = "Pulp Fiction is an awesome movie!";

alert(theBigString.substr(5)); // Fiction is an awesome movie!

There are a few more variations of values you can pass in for substr, but these are the big ones.

Splitting a String/split

That which you can concatenate, you can also split apart. I am pretty sure a wise person once said that. Another way you can split apart a string is by using the split method. Calling this method on a string returns an array of substrings. These substrings are separated by a character or Regular Expression (aka RegEx) that you use to determine when to split apart your string.

Let’s look at a simple example where this makes more sense:

var inspirationalQuote = "That which you can concatenate, you can
  also split apart."
;

var splitWords = inspirationalQuote.split(" ");
alert(splitWords.length); // 10

In this example, we are splitting the inspirationalQuote text on the space character. Every time a space character is encountered, what is left of the string before it is removed and made an item in the array that gets returned by this method.

Here is another example:

var days = "Monday,Tuesday,Wednesday,Thursday,Friday,
  Saturday, Sunday"
;

var splitWords = days.split(",");
alert(splitWords[6]); // Sunday

We have the days variable, which stores a string of days separated only by a comma. If we wanted to separate out each day, we could use the split method with the separator character being the comma. The end result is an array of seven items where each item is the day of the week from the original string.

You’ll be surprised at how often you will find yourself using the split method to break apart a sequence of characters that can be as simple as a sentence or something more complex like data returned from a web service.

Finding Something Inside a String

If you ever need to find a character or characters inside a string, you can use the indexOf, lastIndexOf, and match methods. Let’s look at the indexOf method first.

What the indexOf method does is take the character(s) you are looking for as its argument. If what you are looking for is found, it returns the index position in the string where the first occurrence...occurs. If no matches are found, this method gifts you with a –1. Let’s look at an example:

var question = "I wonder what the pigs did to make these birds so
  angry?"
;

alert(question.indexOf("pigs")); // 18

I am trying to see if pigs exist in my string. Because what I am looking for does exist, the indexOf method lets me know that the first occurrence of this word occurs at the 18th index position. If I look for something that doesn’t exist, like the letter z in this example, a –1 gets returned for:

var question = "I wonder what the pigs did to make these birds so
  angry?"
;

alert(question.indexOf("z")); // -1

The lastIndexOf method is very similar to indexOf. As you can guess by the name, lastIndexOf returns the last occurrence of what you are looking for:

var question = "How much wood could a woodchuck chuck if a
  woodchuck could chuck wood?"
;

alert(question.lastIndexOf("wood")); // 65

There is one more argument you can specify to both indexOf and lastIndexOf. In addition to providing the characters to search for, you can also specify an index position on your string to start your search from:

var question = "How much wood could a woodchuck chuck if a
  woodchuck could chuck wood?"
;

alert(question.indexOf("wood", 30)); // 43

The last thing to mention about the indexOf and lastIndexOf methods is that you can match any instance of these characters appearing in your string. These functions do not differentiate between whole words or what you are looking for being a substring of a larger set of characters. Be sure to take that into account.

Before we wrap this up, let’s look at the match method. With the match method, you have a little more control. This method takes a Regex as its argument:

var phrase = "There are 3 little pigs.";
var regexp = /[0–9]/;

var numbers = phrase.match(regexp);

alert(numbers[0]); // 3

What gets returned is also an array of matching substrings, so you can use your Array ninja skills to make working with the results a breeze. Learning how to work with regular expressions is something that we’ll look at much later.

Upper and Lower Casing Strings

Finally, let’s end this coverage on Strings with something easy that doesn’t require anything complicated. To uppercase or lowercase a string, you can use the appropriately named toUpperCase and toLowerCase methods. Let’s look at this example:

var phrase = "My name is Bond. James Bond.";

alert(phrase.toUpperCase()); // MY NAME IS BOND. JAMES BOND.
alert(phrase.toLowerCase()); // my name is bond. james bond.

See, told you this was easy!


Image Tip

Just a quick reminder for those of you reading these words in the print or e-book edition of this book: If you go to www.quepublishing.com and register this book, you can receive free access to an online Web Edition that not only contains the complete text of this book but also features a short, fun interactive quiz to test your understanding of the chapter you just read.

If you’re reading these words in the Web Edition already and want to try your hand at the quiz, then you’re in luck – all you need to do is scroll down!


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.157.6