However, in case you are here only for the solution use this link.
- Converting strings to array using split
- Limitations & Caveats
- Other Related Concepts
Initially, the only method available for this was
split(). However, after the addition of ES6, alternative methods were introduced that could be used to convert string to array.
Although in this tutorial we focus on the method using
split(), the other methods that can be used are
Converting string to array using split:In this method, we use
split()methods take in a delimiter as a parameter and based on the specifying value the string is split.
Syntax of split:
stringrefers to the original string that we are looking to convert.
delimiter- Optional, the string will be split based on this value. In case it is left empty, an array containing each character is returned.
limit- Optional, an integer value indicating how many times the string needs to be split.
Code & Explanation:
let str1 = "Hire the top 1% freelance developers"; const split_string = str1.split(" "); console.log(split_string) //Output = ["Hire", "the", "top", "1%", "freelance", "developers"]
In the above code, we have passed
" "as the delimiter and an array split by each space is returned.
","is a delimiter.
As shown above, an array containing each individual character is returned.
let str1 = 'Freelance Developers'; const split_string = str1.split(""); console.log(split_string) //Output = ["F", "r", "e", "e", "l", "a", "n", "c", "e", " ", "D", "e", "v", "e", "l", "o", "e", "p", "r", "s"]
Next, let's take a look at an example using the limit parameter.
As you can see, the values after the limit were not split. However, keep in mind that the limit does not refer to the index but rather the 4th occurrence of the delimiter.
let str1 = "Hire the top 1% freelance developers"; const split_string = str1.split(" ",4); console.log(split_string) //Output = ["Hire", "the", "top", "1%"]
Limitation & Caveats:
- If no delimiter is passed the entire string is returned as one element in an array and if an empty string
""is passed, the string splits each character and an array.