By Parth Patel on Jul 22, 2022
1. Convert String to Array using split() method
The split() method returns an array of substrings after splitting the given string by the separator you provide. Note that, split() method does not modify the original string rather returns the array.
- Separator - (Optional). A specific character or regular expression used to split a string. If no parameter is passed, then entire string will be returned as is.
- Limit - (Optional). An integer that specifies the maximum number of substrings returned in the array. Remaining substrings will be ignored.
Let’s see different examples:
Comma as a separator: If you provide comma as parameter to the split() method then it will split the string by comma. Normally this is used to parse csv row data.
let users = 'john, sam, tom, kim'; let arr = users.split(', '); // split string on comma space console.log( ar ); // [ "john", "sam", "tom", "kim"]
let str = 'abcdefg'; let arr = str.split('') console.log(arr); // ['a','b','c','d','e',f','g']
Regular Expression (Regex) as a separator: The regex is a very powerful tool and can be used as a separator to split string to array of substrings as shown below:
let paragraph = 'Good Morning! What is your name? My name is Tom.'; let sentences = paragraph.split(/[!,?,.]/); console.log(sentences); // [ "Good Morning", "What is your name", "My name is Tom", "" ]
Split string only on first instance of specified character:
In this example, separator contains capturing parentheses, hence matched results contains comma along with rest of everything. Hence, it returns rest of the users as combined string.
let users = 'john, sam, tom, kim'; let arr = users.split(/,(.*)/s); // split string on comma space console.log( arr ); // [ "john", " sam, tom, kim", ""]
2. Convert String to Array of characters using Array.from() method
let str = 'Good Morning'; let arr = Array.from(str); console.log(arr); //[ "G", "o", "o", "d", " ", "M", "o", "r", "n", "i", "n", "g" ];