What is split() Method in JavaScript ?
Last Updated :
12 Feb, 2024
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 or undefined
, 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 most limit + 1
elements. If omitted or undefined
, 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' ]
Share your thoughts in the comments
Please Login to comment...