“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:
Example 1: Splitting a Normal String
Create a variable that stores a string:
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”:
Finally, print the split string on the console using the “for” loop for iterating the array:
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”:
Use “@” as a separator in the “split()” method to split the string:
Lastly, print the substrings on the console by iterating the resultant array that is stored in the “explodedString” using the “for” loop:
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.