How to convert string to array in JavaScript
You can convert a string to an array in JavaScript using the split() method. This method splits a string into an array of substrings based on a delimiter or regular expression. The example is given below.
<script>
let myString = 'hello world';
let myArray = myString.split(' ');
console.log(myArray); // Output : ['hello', 'world']
</script>
In the above example, we use the split() method with a space delimiter to split the string myString into an array of two elements ['hello', 'world']. You can also split a string on other delimiters like commas, dashes, or even regular expressions.
4 ways to convert a string to an array in JavaScript. #
We can use the following four common methods to convert a string to an array in JavaScript
- Using split() method.
- Using Array.from() method.
- Using spread operator.
- Using Array.prototype.slice.call() method.
Convert string to array using split() method. #
The split() method is the most commonly used method to convert a string to an array. It splits a string into an array based on a delimiter or regular expression.
<script>
let myString = 'hello, world';
let myArray = myString.split(',');
console.log(myArray); // Output : ['hello', 'world']
</script>
Convert string to array using Array.from() method. #
The Array.from() method creates a new, shallow-copied Array instance from an array-like or iterable object, such as a string.
<script> let myString = 'hello'; let myArray = Array.from(myString); console.log(myArray); // Output : ['h', 'e', 'l', 'l', '0'] </script>
Convert string to array using spread operator. #
The spread operator can also be used to convert a string to an array.
<script> let myString = 'hello'; let myArray = [...myString]; console.log(myArray); // Output : ['h', 'e', 'l', 'l', '0'] </script>
Convert string to array using Array.prototype.slice.call() method #
The slice() method can be used on an array to create a shallow copy of a portion of an array into a new array object, but when it is applied to a string, it converts the string to an array.
<script> let myString = 'hello'; let myArray = Array.prototype.slice.call(myString); console.log(myArray); // Output : ['h', 'e', 'l', 'l', '0'] </script>
- You can use the split() method to split a string into an array based on a delimiter or regular expression.
- The split() method does not modify the original string, but instead returns a new array based on the split.
- By default, the split() method splits the string based on whitespace.
- You can split a string on other delimiters like commas, dashes, or even regular expressions.
- When splitting on a regular expression, you can use capture groups to include the delimiter in the resulting array.
- If you want to split a string into individual characters, you can use the string's split() method.
