Tuesday, October 26, 2010

Javascript function Equivalent to PHP explode() function

We can explode a string into an array using the PHP explode() function. The javascript equivalent function is split() which is slightly different from PHP explode().


PHP explode() function works like this.

$longstring = "codesbyme.blogspot.com";
/**
* we are dividing the string by the dot(.). instead of the dot
* you can have any character which is in your string
* Eg: space, @, #, etc...
$words = explode(".", $longstring); // now $words is an array.

echo $words[0]; //prints "codesbyme"
echo $words[1]; //prints "blogspot"
echo $words[2]; //prints "com"

Now lets see how is the Javascript split() function works. The syntax of this function is slightly different from the PHP explode().

var longstring = "codesbyme.blogspot.com";
var words = longstring.split('.');

/*
words[0] = codesbyme
words[1] = blogspot
words[2] = com
*/

No comments:

Post a Comment