PHP explode equivalent for javascript

→ Are you a new visitor? Please visit the page guidance for new visitors ←

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.

Solution

We would use the function split to do this, see bellow example:

Output

Now you have an array with each of your parts of the string and you can access it directly:

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.

Request an article ←