JavaScript String Split Function
The ability to split up a string into separate chunks has been supported in many programming languages, and it is available in JavaScript as well. If you have a long string like "Bobby Susan Tracy Jack Phil Yannis" and want to store each name separately, you can specify the space character " " and have the split function create a new chunk every time it sees a space.
Split Function: Delimiter
The space character " " we mentioned will be our delimiter and it is used by the split function as a way of breaking up the string. Every time it sees the delimiter we specified, it will create a new element in an array. The first argument of the split function is the delimiter.
Simple Split Function Example
Let's start off with a little example that takes a string of numbers and splits when it sees the number 5. That means the delimiter for this example is 5. Notice that the split function returns an array that we store into 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:
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:
Found Something Wrong in this Lesson?Report a Bug or Comment on This Lesson - Your input is what keeps Tizag improving with time! |