Sometimes, we want to get a character array from a string.
In this article, we’ll look at how to get a character array from a string.
String.prototype.split
A string instance’s split
method lets us split a string by any separator.
If we want to get a character array from a string, we can use the split
method with an empty string.
For instance, we can write:
const output = "Hello world!".split('');
console.log(output);
Then output
is:
["H", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d", "!"]
as a result.
Spread Operator
Another way to split a string into a character array is the spread operator.
We can do this since a string is an iterable object.
To use it, we write:
const output = [..."Hello world!"]
console.log(output);
Then we get the same value for output
as before.
RegExp u flag
We can also use the string split
method with a regex to split a string into a character array.
For instance, we can write:
const output = "Hello world!".split(/(?=[sS])/u);
console.log(output);
s matches any whitespace and S matches any non-whitespace character.
And the /u
flag lets us do searches with Unicode strings properly.
?=
is the followed by quantifier.
So we search for anything that follows a whitespace or non-whitespace character and split them.
And so we get the same result as before.
for-of Loop and Array.prototype.push
Since a string is an iterable object, we can for use the for-of loop to loop through each character.
For instance, we can write:
const output = [];
for (const s of "Hello world!") {
output.push(s);
}
console.log(output);
s
has the character from the string.
In the loop body, we call output.push
to push character s
into the output
array.
So we get the same result as before.
Array.from
The Array.from
method is a static array method that lets us convert an iterable object into an array.
So we can use it to convert a string into a character array.
For example, we can write:
const output = Array.from("Hello world!")
console.log(output);
And we get the same value for output
as before.
Conclusion
There’re many ways to convert a JavaScript string into a character array.
This includes array methods, spread operator, and loops.