String Handling 2Using the split method
Notice that the slashes coud be used as a way to divide the string into three parts. You could separate the home directory, the file directory, and the file name for the program. To actually do this, we can use the split method. As we did with the charAt and indexOf methods, we take the variable name of the string and add a dot-- and then call the split method:
var where_is_mytool="home/mytool/mytool.cgi"; var mytool_array=where_is_mytool.split("/");
As you can see the split method takes a parameter, which is the character we wish to use to divide the original string. In this case, it is the "/" character. You will also notice that what we get back will be an array (notice the variable we hold the result in is called mytool_array). This array holds the three parts, with the first part held in a variable called mytool_array. So, the first element is zero for the arrays you create with split, just like many others we have seen. Knowing this, we can now use the parts which we get from the split in some way:
This one will just give us an alert with the three parts when we click a button. You can see it in action using the button below:
Another thing to remember is that there are times when you will not know how many parts the array will have once it is split (for example, if a viewer enters the information in a prompt). To be sure you get them all, you can use a loop and the length method to get all of them. For example:
The example is below, give it a try:
This validates to some degree, but it doesn't keep a viewer from using a space once and then doing something else. It could still not be quite right if someone types in "red greenorange,blue". This would give back one alert with "red" and another with "greenorange,blue". Still, it will do the job for the most part, and uses some of the things we learned in earlier sections.
Well, that does it for now, let's move on to Screen Resolution Detection!
||By: John Pollock||