Table of Contents
- Code and explanation
- Closing thoughts
Code and Explanation:
The code to split a string in is fairly straightforward, let's take a look:
Here “string” refers to the string you are looking to split. The other terms are parameters we take a look at below.
- Separator - Optional. A specific character, regular expression used to split a string. If not passed, the entire string would be returned.
- Limit - Optional. An integer that specifies the number of splits. Subsequent occurrences of the separator are not included.
It returns an array containing the substrings. If a separator is not passed, the array will contain one element containing the entire string.
let Flexiple = 'Hire top freelance developers' let week = 'Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday' let flexiplelist = Flexiple.split(" ") let weeklist = week.split(",") let flexiplelist2 = Flexiple.split() let weeklist2 = week.split(",",3) console.log(weeklist) console.log(flexiplelist) console.log(flexiplelist2) console.log(weeklist2)
As you can see we have defined two strings, the first one is separated by a space and the next string is separated by a comma.
The output for the above code is:
> Array ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] > Array ["Hire", "top", "freelance", "developers"] > Array ["Hire top freelance developers"] > Array ["Monday", "Tuesday", "Wednesday"]
For the first two arrays, we have used their respective separators.
For the third array, we have not passed a separator and hence the array contains one element containing the entire string.
And for the final array, we have passed a limit and hence only 3 substrings are returned.
This method is useful when trying to split a string based on a pattern. However, in case you wish to split it based on an index you can use the slice methods.