Search This Blog

Thursday, 20 December 2012

JavaScript String Split Function

JavaScript String Split Function

The ability to divide a string into individual parts is a feature supported by many programming languages, including JavaScript. For instance, if you have a long string like "Bobby Susan Tracy Jack Phil Yannis" and want to store each name separately, you can use the split function. By specifying the space character " ", the function will create a new segment each time it encounters a space.

Split Function: Delimiter

The space character " " serves as our delimiter, which the split function uses to divide the string. Each time the function encounters the specified delimiter, it creates a new element in an array. The first argument of the split function is the delimiter itself.

Simple Split Function Example

Let's begin with a simple example where we take a string of numbers and split it at every occurrence of the number 5, making 5 the delimiter in this case. The split function returns an array, which we then store in the variable mySplitResult.

JavaScript Code:

<script type="text/javascript">
var myString = "123456789";

var mySplitResult = myString.split("5");

document.write("The first element is " + mySplitResult[0]); 
document.write("<br /> The second element is  " + mySplitResult[1]); 

</script>

Display:

The first element is 1234
The second element is 6789
Make sure you realize that because we chose the 5 to be our delimiter, it is not in our result. This is because the delimiter is removed from the string and the remaining characters are separated by the chasm of space that the 5 used to occupy.

Larger Split Function Example

Below we have created a split example to illustrate how this function works with many splits. We have created a string with numbered words zero through four. The delimiter in this example will be the space character " ".

JavaScript Code:

<script type="text/javascript">
var myString = "zero one two three four";

var mySplitResult = myString.split(" ");

for(i = 0; i < mySplitResult.length; i++){
 document.write("<br /> Element " + i + " = " + mySplitResult[i]); 
}
</script>

Display:

Element 0 = zero
Element 1 = one
Element 2 = two
Element 3 = three
Element 4 = four

No comments:

Post a Comment