JavaScript – Split a String
To split a string into an array of substrings in JavaScript, where the splitting of this string is done based on a separator, call split() method on this string, and pass the delimiter as first argument.
Syntax
The syntax to split a string str
with a specific separator string is
str.split(separator)
split() method returns an array of strings.
We can also limit the number of splits done. Pass an integer as second argument to split() method, which specifies the limit on the length of returned array.
str.split(separator, limit)
Examples
In the following examples, we go through different scenarios of splitting a string, based on separator, limiting the number of splits, etc.
Split a String with Comma as Separator
In the following example, we take a string str and split this string with comma character as separator.
index.html
Split a String with a Word as Separator
In the following example, we take a string str and split this string with 'abc'
as separator.
index.html
Split a String with Empty String as Separator
If an empty string is given as separator to split() method, then split() method splits the given string between each character.
index.html
Limit Number of Parts into which the String Splits into
We will take a string and split it using comma as separator. Also, we will limit the number of splits in returned array to 3.
index.html
Conclusion
In this JavaScript Tutorial, we learned how to split a string into parts (an array) in JavaScript, using split() method, with examples.