In JavaScript, you can use the built-in split() method to split a string into an array of substrings based on a specified delimiter:
string.split(separator, limit)
Parameters
Parameter | Description |
---|---|
separator | Optional. Specifies the character(s) or regular expression used to split the string. The default value is an empty string (“”). |
limit | Optional. Specifies the maximum number of splits to be made. |
Examples
Split a string with commas and spaces
The code:
const colors = "red, green, blue, yellow, orange, purple, pink"
const colorArray = colors.split(", ")
console.log(colorArray)
Output:
[
'red', 'green',
'blue', 'yellow',
'orange', 'purple',
'pink'
]
Using split() with the limit parameter
The code:
let str = "apple,banana,slingacademy.com";
let arr = str.split(",", 2);
console.log(arr);
Output:
["apple", "banana"]
In the example above, the split() method is used with a limit parameter of 2, which splits the string into an array of 2 substrings.
Using the split() method with regular expressions
You can use regular expressions to create complex and complicated splitting patterns, such as splitting a string based on any whitespace character (spaces, tabs, line breaks):
let str = "Welcome to slingacademy.com. This website is dedicated to learning JavaScript. We have a lot of JavaScript tutorials for beginners and advanced learners. We also have a lot of JavaScript projects for you to practice your JavaScript skills.";
let arr = str.split(/\s+/);
console.log(arr);
Output:
[
'Welcome', 'to', 'slingacademy.com.',
'This', 'website', 'is',
'dedicated', 'to', 'learning',
'JavaScript.', 'We', 'have',
'a', 'lot', 'of',
'JavaScript', 'tutorials', 'for',
'beginners', 'and', 'advanced',
'learners.', 'We', 'also',
'have', 'a', 'lot',
'of', 'JavaScript', 'projects',
'for', 'you', 'to',
'practice', 'your', 'JavaScript',
'skills.'
]
Alternatives
Besides the split() method, there are some other solutions for splitting a string into an array. However, they all have limitations and only fit some special use cases.
Using the spread operator
Example:
let str = "hello";
let arr = [...str];
console.log(arr);
Output:
["h", "e", "l", "l", "o"]
Using Array.from()
Example:
let str = "hello";
let arr = Array.from(str);
console.log(arr);
Output:
["h", "e", "l", "l", "o"]
I hope this helps! Leave a comment if you have any more questions.