codedamn

How to convert a string to an Array in JavaScript?

How to convert a string to an Array in JavaScript?

Hey readers, In this article we will discuss various ways in which we can convert a string to an array. Let’s get started without any further delay.

Live New Year Sale. Become The Best JavaScript Developer 🚀
Get access to hunderes of practice JavaScript courses, labs, and become employable full-stack JavaScript web developer.
  • Free money-back guarantee
  • Unlimited access to all platform courses
  • 100's of practice projects included
  • GPT-3 Based Instant AI Help
  • Structured Full-Stack Web Developer Roadmap To Get A Job
  • Exclusive community for events, workshops
Go Pro Now (50% Discount For Limited Time)

Introduction

In any programming language, a string generally represents a group of characters. A string is nothing but text. The primitive data types of javascript are string, undefined, symbol, number, bigint, boolean and null. Strings are generally enclosed with double quotes or single quote.

An array is a single special variable that can store multiple elements. It contains an ordered list of elements that can be accessed by their respective index. A JavaScript array contains elements from all types of data types that include strings, boolean, numbers, etc. There is no need of specifying the number of elements in the array well before the array is created.

Ways to convert string to an array

Let us discuss some of the ways in which we can convert a string to an array

split() string method

We can use this method to convert a string to an array. This method splits the string according to the parameters passed inside it and returns the array. There will be no change in the original array. Let us discuss the syntax of this method.

Syntax:

string.split(separator, limit)
Code language: JavaScript (javascript)

Let us understand each parameter in the syntax.

Separator:

It is an optional parameter. In the separator, we usually put the pattern that describes where the split should occur in the string. If the separator is not given, then the entire string becomes the only element of the array.

Limit:

It is an optional parameter. This parameter contains the integer specifying a limit on the number of substrings in the array.

Return value:

An array of strings is returned with splitting at the point where the separator occurs.

We understand things better with examples. So let us understand the split string method with the help of some examples.

Example 01

let str1 = 'codedamn' let array1 = str1.split(); console.log(array1);
Code language: JavaScript (javascript)

Output:

['codedamn']
Code language: Bash (bash)

In the above example, we have not given any separator parameter. So entire string became the only element of the array.

Example 02

let str2 = 'codedamn' let array2 = str2.split(''); console.log(array2);
Code language: JavaScript (javascript)

Output:

["c", "o", "d", "e", "d", "a", "m", "n"]
Code language: Bash (bash)

In the above case, the string gets split wherever ‘‘ occurs in the string, and all those substrings are made the elements of the array. So here each letter of the string is an element of the array.

Example 03

const str3 = 'I learn coding from codedamn' let array3 = str3.split(' '); console.log(array3);
Code language: JavaScript (javascript)

In the above case, the string gets split wherever ‘ ‘ occurs in the string, and all those substrings are made the elements of the array.

Output:

['I', 'learn', 'coding', 'from', 'codedamn']
Code language: Bash (bash)

Example 04

const str4 = 'I learn coding from codedamn' let array4 = str4.split(' ',3); console.log(array4);
Code language: JavaScript (javascript)

Output:

['I', 'learn', 'coding']
Code language: Bash (bash)

In the above case, we have specified the limit to 3 and the string splits wherever ‘ ‘ occurs in the string. So only the first three elements of the array have been printed.

Array.from() method

We can use the Array.from() method to convert a string to an array. It is a built-in method of JavaScript. We have to pass the string to Array.from() in order to convert it to an array. We can use Array.from() method to get an array by passing any object that is iterable as a parameter. A string is an iterable object in JavaScript. Hence we can use this method. Let us understand the syntax of the Array.from() method.

Syntax:

Array.from(object, Function, this)
Code language: JavaScript (javascript)

Object:

It is a required parameter. We can pass any object that is iterable as a parameter that needs to be converted to an array.

Function:

This is an optional parameter. We can pass a function as a parameter that is called on each element of the array.

this:

This is also an optional parameter. Its value acts as this, for the function we have called as the second parameter.

Let us understand it with the help of some examples.

Example 01

const str = 'codedamn' const str1 = Array.from(str); console.log(str1);
Code language: JavaScript (javascript)

Output:

["c", "o", "d", "e", "d", "a", "m", "n"]
Code language: Bash (bash)

Example 02

let str1 = '725'; str2 = Array.from(str1,element=>element+2); console.log(str2)
Code language: JavaScript (javascript)

Output:

['72', '22', '52']
Code language: Bash (bash)

LOL, Got surprised by the output right? It is because we have passed the string ‘725’ as the object parameter. So when we add 2 for each element of the array with the help of a function, string concatenation takes place instead of the mathematical addition.

object.assign() method.

We can convert a string to an array using the object.assign() method in following way. Using this method will copy all the string properties to the new array. Let us understand it with the help of an example

let str = 'Codedamn'; let chars = Object.assign([], str); console.log(chars);
Code language: JavaScript (javascript)

Output:

['c', 'o', 'd', 'e', 'd', 'a', 'm', 'n']
Code language: Bash (bash)

The spread operator

We can convert a string to an array using the spread operator. The spread operator extracts each and every character of the string and converts them as elements of an array and returns the array. Let us understand it with the help of an example

const str = 'Codedamn'; const chars = [...str]; console.log(chars);
Code language: JavaScript (javascript)

Output:

['c', 'o', 'd', 'e', 'd', 'a', 'm', 'n']
Code language: Bash (bash)

Using loops

We can use loops to convert a string to an array. First, we have to create an empty array. Now using loops, we have to iterate through the string and push each character of the string to the empty array we have created. This is the slowest method out of all the above methods as using loops increases time complexity. Let us see how we can empty an array using for loop, for… of… loop, and for… in… loop. There is not much change in logic for all three ways but the syntax changes a bit.

The for… of… loop

We can use the for… of… loop to empty an array in JavaScript. Let us see how with the help of an example.

let str1 = 'codedamn' let array1 = [] for(let i of str){     arr.push(i); } console.log(array1)
Code language: JavaScript (javascript)

Using for… in… loop

We can use the for… in… loop to empty an array in JavaScript. Let us see how with the help of an example.

let str1 = 'codedamn' let array1 = [] for(let i in str1){ array1.push(str1[i]); } console.log(array1)
Code language: JavaScript (javascript)

The use of for loop

We can use the for loop to empty an array in JavaScript. Let us see how with the help of an example.

let str1 = "codedamn"; let array1 = []; for (let i = 0; i < str.length; i++) {array1.push(str[i]); } console.log(array1)
Code language: JavaScript (javascript)

In all the above cases output is the same and it is like shown below

['c', 'o', 'd', 'e', 'd', 'a', 'm', 'n']
Code language: Bash (bash)

Conclusion

In this article, we have discussed some of the ways in which we can convert a string to an array in JavaScript. The first method i.e the split string method is the most used method while converting a string to an array. As a developer, you are going to use all of these methods a lot. That’s it for this article. Do not stop learning here. Just binge-watching video tutorials don’t work out if you want to expertise in JavaScript. Do check out this JavaScript course on codedamn where learning takes place with lots of hands-on practice on inbuilt playgrounds with video tutorials as well.

Do check out the all-new free course on JavaScript under the hood at codedamn to Learn about advanced JavaScript and how it works under the hood.

Live New Year Sale. Become The Best JavaScript Developer 🚀
Get access to hunderes of practice JavaScript courses, labs, and become employable full-stack JavaScript web developer.
  • Free money-back guarantee
  • Unlimited access to all platform courses
  • 100's of practice projects included
  • GPT-3 Based Instant AI Help
  • Structured Full-Stack Web Developer Roadmap To Get A Job
  • Exclusive community for events, workshops
Go Pro Now (50% Discount For Limited Time)

Learn programming on codedamn

Codedamn is an interactive coding platform with tons of sweet programming courses that can help you land your first coding job. Here's how:

Programming is one of the most in-demand jobs today. Learning to program can change your future. All the best!

Sharing is caring

Did you like what Manish wrote? Thank them for their work by sharing it on social media.