Convert String to Array in JavaScript

Convert String to Array in JavaScript | The most compelling data structure in JavaScript is an array. By transforming strings into arrays, we discovered that we could solve a lot of algorithms. we then considered compiling and contrasting other approaches to accomplish the same.

String to Array in JavaScript Using split()

The split() method is always used to convert strings to arrays, but since the release of ES6, we may use many other tools. Let’s go over the advantages and disadvantages of each technique one at a time.

Syntax:-
str.split(separator, limit)

Example:- Using JavaScript’s split() function, we will create a character array from a string in this instance.

const myFavFruit = "Mango";
const myFavFruitArray = myFavFruit.split("");
console.log(myFavFruitArray);

Output:-

[ ‘M’, ‘a’, ‘n’, ‘g’, ‘o’ ]

We can split strings using characters or whitespace, another benefit of this approach. Here is an illustration of how you can do it.

String to Array in JavaScript Using Spread Syntax ([…str])

Rare Unicode characters need to respond better to this strategy. The MDN paper has been modified to work with Unicode if we include the u flag. However, this technique returns the Unicode of the characters instead of the actual characters, which may make our job a little more complex.

Method 2: Using spread syntax ([…str])

The ES2015 feature that facilitates the transition is this one.

Example:

const myFavFruit = "Mango";
const myFavFruitArray = [...myFavFruit];
console.log(myFavFruitArray);

Output:-

[ ‘M’, ‘a’, ‘n’, ‘g’, ‘o’ ]

String to Array in JavaScript Using Array.from()

The Array.from() method copies an iterable or array-like object into a new, shallow-copied instance of an Array. When dealing with rare characters, this strategy will be acceptable.

const myFavFruit = "Mango";
const myFavFruitArray = Array.from(myFavFruit);
console.log(myFavFruitArray);

Output:-

[ ‘M’, ‘a’, ‘n’, ‘g’, ‘o’ ]

String to Array in JavaScript Using Array.push()

Even though we have many options, we had to bring up this dated technique where we push the string elements using the for loop and array method push().

Even if it’s not the cleanest approach, it’s worth mentioning for those who want to avoid JavaScript’s shifting complications (Although we would prefer other ways).

const c = "Honda";
const a = [];
for (const c2 of c) {
  a.push(c2);
}
console.log(a);

Output:-

[ ‘H’, ‘o’, ‘n’, ‘d’, ‘a’ ]

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *