Friday, April 22, 2011

jQuery Split revisited

Split method split the string into array of substring and return a new array. The basic syntax for split method is,


1
string.split(separator, limit)
It takes 2 parameters,
1. separator - This is optional. It specifies the character to use for splitting the string. If omitted, the entire string will be returned.
2. limit - This is also optional. This will be an integer value that specifies the number of splits to be made.

Let's see some examples.

Example 1:

1
2
var element = 'jQuery By Example Rocks!!';
var arrayOfStrings = element.split();
In this example, I have not used any separator and not defined any element. So the whole string will be returned back to arrayOfStrings variable.

Example 2:
?
1
2
var element = 'jQuery By Example Rocks!!';
var arrayOfStrings = element.split(" ");
In this example, I have passed space as delimiter or separator to split the string. So arrayOfStrings variable will have 4 items.

1
2
3
4
arrayOfStrings[0] = "jQuery"
arrayOfStrings[1] = "By"
arrayOfStrings[2] = "Example"
arrayOfStrings[3] = "Rocks!"
Example 3:

1
2
var element = 'jQuery By Example Rocks!!';
var arrayOfStrings = element.split(" ",3);
In this example, I have passed space as delimiter or separator to split the string and also passed limit as 3. So arrayOfStrings variable will have only 3 items.

1
2
3
arrayOfStrings[0] = "jQuery"
arrayOfStrings[1] = "By"
arrayOfStrings[2] = "Example"
Hope this post provides you enough information about Split method.