JavaScript Chapter 5 Javascript String Manipulation

Javascript Strings - Changing Case


A big part of your life as a programmer is manipulating strings of text. To help you with this, Javascript comes with lots of inbuilt methods you can use. We'll take a look these in this and the next few sections. Before you go any further, though, create a new web page with two SCRIPT tags in the HEAD section. You can use the template you created in an earlier section.

Changing Case

If you need to change the case of a string of text you can use the two inbuilt methodstoUpperCase and toLowerCase. They are fairly easy to use. Add the following to your two SCRIPT tags:
<SCRIPT LANGUAGE = "Javascript">
var postcode = "sr2 4jh";
var new_postcode = postcode.toUpperCase();
document.write( new_postcode );
</SCRIPT>
The first line sets up a variable called postcode. Imagine you've got this value from a text box on a form. You want to make sure that the letters are all uppercase. You can convert them by usingtoUpperCase (note the capital letters "U" and "C"). But look at how it's done:
var new_postcode = postcode.toUpperCase();
To the right of the equal sign you type the variable you want to convert. After a dot you type the method name, toUpperCase, followed by a pair of empty round brackets. End the line in the usual way with a semicolon.
Another thing to notice here is that we have a new variable to the left of the equal sign. The newly converted value will be placed in the variable we've called new_postcode. The reason that we're storing the converted value into a new variable is because in Javascript strings are immutable. This means that you can't actually change any characters in a string. What Javascript does instead is to create an entirely new string for you, leaving the original untouched. As an example, add the another document.write to the end of your code, as well as a BR tag to the first one:
document.write(new_postcode + "<BR>");
document.write( postcode );
When you run your script in a web browser new_postcode will be SR2 4JH while postcode will be sr2 4jh. The original postcode variable has been left untouched.
However, you can do this:
var postcode = "sr2 4jh";
postcode = postcode.toUpperCase();
But be aware that you are creating a new string to the right of the equal sign and storing it back into the postcode variable.
Exercise
Change the postcode variable to SR2 4JH on the first line of your code. Now use toLowerCase to convert it.

Javascript Strings - indexOf


The indexOf method tells you if a string of text contains a particular character, the @ sign in an email address for example. It won't check every occurrence of the character, but just the first one. If the character can't be found then IndexOf returns a value of -1 (minus 1). If the character is found then the value returned is the position in the string (6th character, for example).

To test out indexOf (capital letter "O"), change your code to this (or create a new web page):
var email = "meme@meme.com";
var at_sign = email.indexOf('@');
document.write( at_sign );
This code sets up a variable to hold an email address. We want to check if the email address contains an @ sign. indexOf is used like this:
var at_sign = email.indexOf('@');
Again, you start on the right of an equal sign, and with the variable you want to check. After a dot, you type IndexOf. In between the round brackets of indexOf you need to type the character or characters you are checking for. The character or characters need to go between quotation marks. (You can check for more than one character, .com, for example. In which case the number returned will be for the first character of your string.)
If you run the script above, you'll find that Javascript returns a value of 4. You might think that the @ sign in our email address is at position 5. However, Javascript starts the count from 0, which is why the answer is 4.
Now delete the @ sign from the email address on the first line of the code. Run the script again and you should find a value of -1 is written to the page.
You can use this information in an IF Statement. Like this:
if ( at_sign == -1 ) {
document.write( "no @ sign in email address" );
}
else {
document.write("email address contains @ sign");
}
The code above just checks the at_sign variable for a value of -1 and takes action accordingly. Add it to your own code and test it out. Put the @ sign back in and rerun your code.

Javascript Strings - charAt


In the previous section, you used indexOf to get the position of one string of text inside another. But if you want the character returned rather than its position number then you can use the Javascript string method charAt. Like this:
if ( at_sign == -1 ) {
document.write( "no @ sign in email address" );
}
else {
var character = email.charAt( at_sign );
document.write( character );
}
The first line of the else part of the IF Statement is now this:
var character = email.charAt( at_sign );
After the email variable we have chartAt. In between its round brackets you need a number. The number is the position in the string you want to grab. Our at_sign variable contains the number 4, which is where the @ sign is in the email address. This character will then be stored in the variable we've called character.
If you want the keyboard code of the character you've just grabbed then you can use charCodeAt instead of charAt:
var character = email.charCodeAt( at_sign );
The character variable will now contain the keyboard code 64 on a UK keyboard.

Javascript Strings - substr


Sometimes, you want to grab characters from a string. For example, you can grab the last four letters from an email address and see if they end in .com. You can do this with the Javascript method substr.

The substr method needs at least one number between its round brackets. This is the position you want to start your search. Optionally, you can add a second number after a comma. This is how many characters you want to grab. If you don't include the second number then Javascript will grab all the characters from your starting position right to the end of the string. Examine the following code:
var email = "meme@meme.com";
var ending = email.substr( 0, 4 );
document.write(ending);
This code grabs 4 characters from the email address, starting at position 0. (Position 0 is the first character in a string.) If you miss out the comma and the 4 but keep the 0 then substr will return all of the email address.
You can start grabbing character from the end of string by typing a negative number. So -4 means grab 4 characters from the end of the string. Here's an example:
var email = "meme@meme.com";
var ending = email.substr( -4 );
document.write(ending);
This grabs the last 4 characters from the email address, which are .com.
A popular use for substr is to cycle through all the letters in a string. In Javascript code previously we checked for an @ sign. But what if the user enters more than one @ sign, in an attempt to deceive us? If we use indexOf it will only tell us the position of the first occurrence of the @ sign. It will stop when it finds just one. By using a loop, an IF statement, and substr, you can go through all the letters of the email address, counting how many @ signs there are. Take a look at this code:
var at_sign = "@meme@meme@.com@";
var counter = 0;
var i;
for ( i=0; i < at_sign.length; i++ ) {
var char = at_sign.substr( i, 1 );
if (char == "@" ) {
counter++;
}
}
document.write("number of times @ appears is: " + counter);
We've set up the email address to have 4 @ signs. We've then set up a counter variable and a loop variable called i. All strings have a length property, which is how many characters a string has. So the first line of our for loop can be this:
for ( i=0; i < at_sign.length; i++ ) {
We're looping until the variable called i is no longer less than the length of the email address stored in the at_sign variable. The i variable increases by 1 each time round the loop. We can use that fact in our substr method:
var char = at_sign.substr( i, 1 );
The first time round the loop the i variable will have a value of 0. So substr will be substr(0, 1). This means start at the first character in the string and grab 1 character. The second time round the loop the i variable will have a value of 1. So substr will be substr(1, 1). Which means start at the second character and grab 1 from that point. Next will be substr(2, 1), which grabs the third character from the email address.
We keep going round and around grabbing 1 character at a time with substr. The IF statement checks if this character is an @ sign. If it is, the counter will get 1 added to it.
So if you need to check every character in a string, study the use of substr above.

Javascript Strings - Split and Join


You can split up strings of text with the Javascript split method. In between the round brackets of split you type an optional delimiter. The delimiter is how the various parts of the string are separated. This might be with a comma, a semicolon, a space, etc. The delimiter needs to go between quote marks. When you split a string you turn it into an array. Let's look at an example:
var email = "me@email_1.com, him@email_2.com, her@email_3.com";
var email_array = email.split(',');
The first line is a list of email addresses. All three are separated by commas. The next line uses the split method. Look at the part after the equal sign:
email.split(',')
We're splitting the variable called email. In between the round brackets of split we have typed a comma between two quote marks. The split method will search the string for commas. It will then place anything before a comma into an array position. After it's done, we'll have an array calledemail_array. Here's a for loop that prints out each email address:
var i;
for ( i=0; i < email_array.length; i++ ) {
document.write( email_array[i] + "<BR>" );
}
The for loop above keeps going round while the variable called i is less than the length of the array. (An array's length is how many positions it has).

The Javascript join Method

You can join strings of text together with the join method. Suppose we wanted our email addresses to be separated by hyphens rather than commas. We can do it like this:
var email = "meme@email_1.com,him@email_2.com,her@email_3.com";
var email_array = email.split(',');
var new_string = email_array.join('-');
document.write(new_string);
The first two lines are the same. But look at the third line:
var new_string = email_array.join('-');
Again, the join method uses a pair of round brackets with a delimiter inside of them. Each position in the email_array will now be joined together with hyphens.
If you wanted no spaces at all between your strings then you can miss out the delimiter and just have two quote marks together.
Mastering the various string methods will really bring your programming skills a lot. To give you more practice with them, try these few exercises.

Exercise - split
The following books have numbers in their titles:
Catch 22
Slaughterhouse 5
Fahrenheit 451
Write a programme to print out just the numbers. You can use arrays, loops, and split to solve this problem.

Exercise - substr
If somebody is using an iPad to surf your site the user agent might read this:
"Mozilla/5.0(iPad; CPU OS 5_0_1 like Mac OS X)"
Write a programme to extract iPad and Mac OS X from the string. You can use substr twice here. Print the answer on one line using document.write.


Comments