Table of Contents
- Code and explanation
- Closing thoughts
- Other Related Concepts
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.
Return Value:It returns an array containing the substrings. If a separator is not passed, the array will contain one element containing the entire string.
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.
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)
The output for the above code is:
For the first two arrays, we have used their respective separators.
> Array ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] > Array ["Hire", "top", "freelance", "developers"] > Array ["Hire top freelance developers"] > Array ["Monday", "Tuesday", "Wednesday"]
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.