What is split() Method in JavaScript ?
In JavaScript, the split()
method is used to split a string into an array of substrings based on a specified separator. It allows you to break a string into smaller parts, which are then stored as elements in an array.
Syntax:
string.split(separator, limit)
string
: The string to be split.separator
: A string or regular expression that specifies where to split the string. If omitted orundefined
, the entire string is treated as a single element in the resulting array.limit
(optional): An integer specifying the maximum number of splits to perform. The array will contain at mostlimit + 1
elements. If omitted orundefined
, all possible splits are made.
Example: Here, the split()
method is called on the str
string with ","
as the separator. This splits the string wherever a comma ,
is found, resulting in an array ["apple", "banana", "orange"]
, with each fruit name as an element.
Javascript
const str = "apple,banana,orange" ; const fruitsArray = str.split( "," ); console.log(fruitsArray); // Output: ["apple", "banana", "orange"] |
Output
[ 'apple', 'banana', 'orange' ]