Javascript: How to split String to character array
By Parth Patel on Jul 22, 2022
In this article, we will discuss how to split string to an array of characters in Javascript. There are multiple ways to convert javascript string to an array of either characters or even substrings.
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.
Syntax:
string.split(separator, limit)
Parameters:
- 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:
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"]
Empty Separator: You can convert string to array of characters in JavaScript by passing empty string as separator to the split() function.
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
The Array.from
method is not commonly used as split() is more than enough and quite simple. But, this method too can convert string to array of characters in Javascript. So, out of curiosity, let’s see an example.
Example
let str = 'Good Morning';
let arr = Array.from(str);
console.log(arr);
//[ "G", "o", "o", "d", " ", "M", "o", "r", "n", "i", "n", "g" ];
Conclusion
There are many different ways to split javascript string to an array of characters or substrings though split() is more than enough. Hope, this article helped.
Adios.