PHP explode equivalent for javascript
PHP explode equivalent for javascript
Very often you have to perform operations on strings to split them, to obtain only a desired piece of it. If the string is formatted in a way that allows you to split, eg. you know the delimiters, you can use the following way to do this.
Problem
Let’s say you have a string delimited by some sort of characters, and you want to split that string after that character to store it into an array.
1 |
var string = 'firstpart_secondpart_thirdpart'; |
Solution
We would use the function split to do this, see bellow example:
1 2 |
var string = 'firstpart_secondpart_thirdpart'; var arrData = string.split("_"); |
Output
Now you have an array with each of your parts of the string and you can access it directly:
1 2 3 |
alert( arrData[0] ); //outputs 'firstpart' alert( arrData[1] ); //outputs 'secondpart' alert( arrData[2] ); //outputs 'thirdpart' |
Note! If an empty string (“”) is used as the separator, the string is split between each character. The split() method does not change the original string.
Browser compatibility
The split function is supported in all major browsers.