Javascript Strings - Split and Join

Five part section: 1 2 3 4 5

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 = ",,";
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:


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 called email_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 = ",,";
var email_array = email.split(',');
var new_string = email_array.join('-');

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.


In the next section, we'll look at how Javascript tackles dates and times.