JavaScript

JavaScript Equivalent to PHP Explode()

explode()” is a well-known PHP function that divides/splits a string into an array of substrings according to a particular delimiter. To perform the same behavior, JavaScript has the “split()” method. By breaking strings into smaller bits, both of these functions make it easier to manipulate and work with them.

This post will illustrate the equivalent of JavaScript’s PHP explode() method.

What is the Equivalent of PHP “explode()” in JavaScript?

The equivalent of the PHP “explode()” function in JavaScript is the “split()” method. The “split()” method in JavaScript can be utilized for splitting/dividing a string into an array of substrings according to a particular separator. It outputs a new array that contains the substrings.

Syntax

The following syntax is utilized for the split() method:

string.split(separator)

Example 1: Splitting a Normal String

Create a variable that stores a string:

var string = "Welcome To JavaScript Tutorial on Linuxhint.";

Now, split the string with the help of the “split()” method with passing a space as a separator. It returns an array of substrings stored in a variable “explodedString”:

var explodedString = string.split(" ");

Finally, print the split string on the console using the “for” loop for iterating the array:

for(var i = 0; i < explodedString.length; i++){
   console.log(explodedString[i]);
}

The output indicates that the string has been successfully split or exploded in multiple substrings based on the specified separator that is “space”:

Example 2: Splitting a String Comprising the Email id

Here, we will split the email string into two parts based on the delimiter/separator “@”. The two parts of the email string are the “user info”, and the “domain name”.

First, store an email string in a variable “string”:

var string = "[email protected]";

Use “@” as a separator in the “split()” method to split the string:

var explodedString = string.split("@");

Lastly, print the substrings on the console by iterating the resultant array that is stored in the “explodedString” using the “for” loop:

for(var i = 0; i < explodedString.length; i++){
   console.log(explodedString[i]);
}

The output displays two parts of the string, “user info” which is “abc123”, and the “domain name” as “gmail.com”:


That’s all about the equivalent of the PHP explode() function in JavaScript.

Conclusion

The JavaScript equivalent to PHP “explode()” is the “split()” method. Both methods are utilized for splitting/dividing a string into an array of substrings depending on a given delimiter or separator. This post illustrated the equivalent of the PHP’s explode() method in JavaScript.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.