Account Log In - Home/Outlines - Books - Contact Us - Support - Employment -

DHTML

JavaScript Programming Fundamentals

Strings

Strings are another very much useful and needed component of JavaScript. Strings are what allow you to do things like print out "Hello, world" like we did previously. This might seem pretty simple, but in fact, we can do much, much more with strings than printing out text on the screen. This lecture will discuss some of the things we can do with strings.

What is a String?

When we talk about strings in JavaScript, we are talking about text strings. You have already seen a string in action when you did the previous exercise of writing out "Hello, world" on your page. As you saw, a string is usually denoted with quotation marks. These can be either double quotes, or single quotes.

Working With Strings

Working with strings in JavaScript is much different than working with numeric values. Numeric values can be added together, multiplied, or subtracted, etc. (more on this in the next lecture). Text strings work a little differently. To see the difference, we will take a numeric value and turn it into a string.

To see this in action, start your own blank HTML page, and put in the necessary <script> tags as we have shown you.

(Note: By now, you should have a blank HTML page with all the <script> tags written out and saved somewhere so that you can easily use it each time you do a new practice exercise.

Let's imagine we are trying to show the use the total amount of money he has to pay for a product. For the sake of convenience, we have already arrived at that number.

var total_money = 100;

// Now, we will add 10 to the number:
total_money = total_money + 10;

// Let's now use our old friend the alert box to spit out the value of total_money.
alert(total_money);

As you can see, the alert showed us a value of 110.

Since this is a numeric value, JavaScript just adds the value of 10 to the variable, which was 100, giving us a new value for total_money of 110. Let's convert total_money into a string, and try it again. We accomplish this with the following line of code:

var total_money_string = String(total_money);

Let's look at this line for a minute.

Note: Make sure you have written the word String with a capital S, otherwise you will get an error. To the case-sensitive JavaScript, string is not the same as String.

So now our script should look like this:

var total_money = 100;

/* Create a new variable called "total_money_string", then assign it the
value of total_money, converted to a string.*/
var total_money_string = String(total_money);

// Now, we will add 10 total_money_string.
total_money_string = total_money_string + 10;

// Use an alert box to show us the new value of total_money_string.
alert(total_money_string);

This should give us a rather unexpected result. The reason is that JavaScript can't add strings together like it does with numbers. Instead, it concatenates them, or puts them together. Even though you added a real number (10) to the string, as soon as the script sees that you are adding something to a string, it concatenates it.

We will show you how to convert strings into numbers a bit later on.

Let's try a little exercise. Say we wanted to write out 3 lines of a popular shakespeare play. We could write it out this way:

document.write("To be or not to be, that is the question: Whether tis nobler in the mind to suffer the slings and arrows of outrageous fortune, Or to take arms against a sea of troubles, and by opposing end them?");

But that's a little long-winded, don't you think? And it is written out as one single line. Instead, we can use string concatenation and variables to our advantage:

// Create some variables with text string values.
var quote1 = "To be or not to be, that is the question: ";
var quote2 = "Whether tis nobler in the mind to suffer the slings and arrows of outrageous fortune, ";
var quote3 = "Or to take arms against a sea of troubles, and by opposing end them? ";

// write this text out to the page.
document.write(quote1 + quote2 + quote3);

Check out this example of the above text.

As you can see, the result doesn't look very nice, and it is still written out as a single line.

Let's look at how we can concatenate variables and text. We already know that the document.write(); method writes text to the page, but it can also write HTML code to the page as well. Let's try the above code again, with a slight modification (modified section in bold):

// Create some variables with text string values.
var quote1 = "To be or not to be, that is the question: ";
var quote2 = "Whether tis nobler in the mind to suffer the slings and arrows of outrageous fortune, ";
var quote3 = "Or to take arms against a sea of troubles, and by opposing end them? ";

// write this text and some HTML out to the page.
document.write(quote1 + "<br />" + quote2 + "<br />" + quote3);

Check out an example of this code here.

As you can see, when you put the variables into the write() method, they are written out. When you add another string (in this case, the <br /> HTML tag) in quotes, it gets concatenated to the previous string.

Searching Strings

It can be very useful to be able to search a string for a particular character. For example, let's say you had a form that asked for the user's email address. You can check to see if is a valid email address by looking for the @ symbol in the string.

Before we get into searching strings though, let's learn another cool JavaScript trick, the prompt() method. A prompt is basically a quick and easy way of getting user input without using a complicated HTML form, so it is good for our current task. The JavaScript prompt pops up a dialog box that asks you for input. The code for our prompt() looks like this:

email_addy = prompt('Please enter your email address','');

The prompt() method contains two basic parts, separated by a comma. Both need to be enclosed in quotes (unless they are variables, of course). The first part contains the text that will be displayed above the text input field, and the second part is what will be in the input text field. (Usually, you leave this blank.)

Check it out in action.

The above example didn't do too much, because we simply put a prompt() method in an onclick event handler, and aren't really doing anything with it. Now we'll assign it a variable, as in the above code, and spit out an alert box with the info.

Click for another demonstration.

The code in that demonstration looks like this:

var email_addy = prompt('Please enter your email address','');
alert ('Your email address is:' + email_addy);

As you might have noticed, whatever you typed in shows up in the alert box. If you typed in "Phhhhht", then that is what you would see. What we really need to do is find a way to search in that string for an @ symbol that would tell us that it's probably a valid email address. Luckily, there is a way to do this. Open up a new HTML page, and start scripting.

We can search a string using the indexOf() method. This method looks through the string to try and find the specified character. If it finds it, it will return its position. If it doesn't, it will return a value of -1. The indexOf() method works like this:

string_to_search.indexOf('some_character');

Let's break it down. You start with the string you want to search, followed by a dot, then the indexOf() method. Inside indexOf(), you put in the character you want to search for, in quotes (unless it's a variable, of course).

So here's our new Script:

// get some user input with a prompt() method.
var email_addy = prompt('Please enter your email address','');

// Search the string for the famous '@' symbol, and assign what it finds to a new variable.
var is_email = email_addy.indexOf('@');

// Spit out the value of is_email with an alert box
alert(is_email);

Your script should prompt you for your address. If you typed it in with an @ symbol, the alert box should contain a value that corresponds to that character's position in the text string. If you didn't, you will get a value of -1.

Here is our example.

BUT WAIT! You've counted the characters from the beginning of the string, and the number doesn't look right! What's going on?

Well, JavaScript doesn't count from 1. JavaScript counts from 0. If you entered me@someplace.com into your prompt, then the indexOf() method would find your @ symbol in position number 2. 'm' = 0, 'e' = 1, and '@' = 2.

As you can see, this is a useful way to find out:

  1. If a character is contained in a string.
  2. The position of that character within the string.

More String Magic

There is yet another string trick we will cover in this lecture, the substring() method. This method takes the form of:

string_to_search.substring(start,end);

What substring() does, is go to the position you specify in the first parameter (yes, those things inside the parentheses are called parameters), and return a portion of the string ending at the position you specify in the second parameter.

Click for an example.

I closed that window on purpose. We don't want you to go looking at the code just yet. :)

Open up another new HTML document and let's start scripting.

The purpose of this exercise it to extract the FQDN (Fully Qualified Domain Name) from a full URL.

How do we do that? Well, for one thing, we know where the FQDN will begin (assuming it's using HTTP://, which we DID ask for). If we count from the left, starting at 0, then the FQDN would start at position 7.

What we don't know, is how long the typed URL will be. Hmmm, this poses a problem. Luckily for us, there is a way to find out how long a string is, and it's really easy to use. We will use the .length property of the string object.

So in your script, type in the following (or copy and paste, if you really must):

// get a URL from the user.
var full_url = prompt('Type in a full URL, including the "HTTP://" part.','');

// search the full_url string from position 7 to the end of the string, wherever that is.
var fqdn = full_url.substring('7',full_url.length);

alert('Your FQDN is: ' + fqdn);

A few notes about the above code.

Cool, isn't it?

That's enough about strings. We'll move on to something else before you get too "strung out" on strings. We will be coming back to strings a little later on in this course for some more string magic.

Strings Summary

Free seminars, open to the public:
Free seminars, open to the public:


DHTML - TOC - Introduction - Books -
JavaScript Programming Fundamentals - Links - Questions - Quiz -
1 - 2 - 3 - 4 - [ 5 ] - 6 - 7 - 8 - 9 -

DHTML - TOC - Introduction - Books -
JavaScript Programming Fundamentals - Links - Questions - Quiz -
1 - 2 - 3 - 4 - [ 5 ] - 6 - 7 - 8 - 9 -