How To Convert String To Array In JavaScript: Methods And Examples

//

Thomas

Affiliate disclosure: As an Amazon Associate, we may earn commissions from qualifying Amazon.com purchases

Want to convert a string into an array in JavaScript? Check out our guide on the different methods you can use, including split(), Array.from(), spread operator, Array.prototype.map() method, and regular expressions, with to help you get started.

Overview of Converting String to Array in JavaScript

JavaScript is a programming language that is widely used for both web development and mobile applications. One of the essential features of JavaScript is the ability to convert a string into an array. In this section, we will look at the definition of a string and an array, as well as the benefits of converting a string into an array.

Definition of String and Array

A string is a sequence of characters that is enclosed in quotation marks. In JavaScript, a string can be created using single quotes (”) or double quotes (“”). An array, on the other hand, is a collection of values that are stored in a single variable. An array can hold any data type, including strings, numbers, and objects.

Benefits of Converting String to Array

Converting a string to an array is beneficial in several ways. First, it enables you to manipulate the string data more easily. For instance, suppose you have a string that contains multiple values separated by commas. By converting the string to an array, you can easily access each value using its index position.

Secondly, converting a string to an array is useful when you need to perform operations that are only available to arrays. For example, you can use the array.prototype.map() method to transform each element in the array and return a new array.

Lastly, converting a string to an array is necessary when you need to sort the data. Sorting a string is not possible since it is a sequence of characters. However, sorting an array is possible since it is a collection of values.

In the next sections, we will look at different methods that can be used to convert a string to an array.

Converting String to Array Using split() Method

The split() method is a built-in function in JavaScript that can be used to convert a string to an array. The split() method takes a delimiter as an argument and splits the string into an array of substrings.

Explanation of split() Method

The split() method is used to split a string into an array of substrings. The delimiter is used to determine where to split the string. The delimiter can be a string or a regular expression. If the delimiter is not specified, the entire string is returned as a single element in the array.

Syntax of split() Method

The syntax for the split() method is as follows:

string.split(delimiter);

Where string is the string to be split, and delimiter is the character or regular expression to use for splitting.

Example of split() Method

Suppose we have a string that contains the names of fruits separated by commas.

const fruits = "apple, banana, cherry, date";

We can use the split() method to convert the string to an array as follows:

const fruitsArray = fruits.split(",");

The result will be an array of fruits:

["apple", "banana", "cherry", "date"]

Converting String to Array Using Array.from() Method

The Array.from() method is another built-in function in JavaScript that can be used to convert a string to an array. The Array.from() method creates a new array from an array-like or iterable object.

Explanation of Array.from() Method

The Array.from() method creates a new array from an array-like or iterable object. In the case of a string, the string is treated as an array of characters, and each character is added as an element in the new array.

Syntax of Array.from() Method

The syntax for the Array.from() method is as follows:

Array.from(arrayLike, mapFunction, thisValue);

Where arrayLike is the array-like object to convert to an array, mapFunction is an optional function that can be used to map each element in the new array, and thisValue is an optional value to use as this when executing the mapFunction.

Example of Array.from() Method

Suppose we have a string that contains the names of animals.

const animals = "catdograbbit";

We can use the Array.from() method to convert the string to an array as follows:

const animalsArray = Array.from(animals);

The result will be an array of animals:

["c", "a", "t", "d", "o", "g", "r", "a", "b", "b", "i", "t"]

Converting String to Array Using Spread Operator

The spread operator is a new feature in JavaScript that was introduced in ES6. The spread operator can be used to convert a string to an array by spreading the characters of the string into an array.

Explanation of Spread Operator

The spread operator is used to spread the elements of an array or iterable object into a new array. In the case of a string, the spread operator is used to spread the characters of the string into an array.

Syntax of Spread Operator

The syntax for the spread operator is as follows:

[...iterable];

Where iterable is the array or iterable object to spread.

Example of Spread Operator

Suppose we have a string that contains the names of cities.

const cities = "New YorkLos AngelesChicago";

We can use the spread operator to convert the string to an array as follows:

const citiesArray = [...cities];

The result will be an array of cities:

["N", "e", "w", " ", "Y", "o", "r", "k", "L", "o", "s", " ", "A", "n", "g", "e", "l", "e", "s", "C", "h", "i", "c", "a", "g", "o"]

Converting String to Array Using Array.prototype.map() Method

The Array.prototype.map() method is a built-in function in JavaScript that can be used to convert a string to an array. The map() method creates a new array by applying a function to each element in the original array.

Explanation of Array.prototype.map() Method

The Array.prototype.map() method is used to create a new array by applying a function to each element in the original array. In the case of a string, the string is treated as an array of characters, and the map() method can be used to transform each character and return a new array.

Syntax of Array.prototype.map() Method

The syntax for the Array.prototype.map() method is as follows:

array.map(callbackFunction, thisValue);

Where array is the array-like object to map, callbackFunction is the function to apply to each element, and thisValue is an optional value to use as this when executing the callbackFunction.

Example of Array.prototype.map() Method

Suppose we have a string that contains the names of countries.

const countries = "usafricachina";

We can use the Array.prototype.map() method to convert the string to an array as follows:

const countriesArray = Array.prototype.map.call(countries, function(x) {
return x.toUpperCase();
});

The result will be an array of countries:

["U", "S", "A", "F", "R", "I", "C", "A", "C", "H", "I", "N", "A"]

Converting String to Array Using Regular Expression

A regular expression is a sequence of characters that defines a search pattern. In JavaScript, regular expressions can be used to split a string into an array.

Explanation of Regular Expression

A is used to define a search pattern. In the case of a string, a regular expression can be used to match a specific character or sequence of characters and split the string into an array.

Syntax of Regular Expression

The syntax for using a regular expression to split a string into an array is as follows:

string.split(regex);

Where string is the string to be split and regex is the regular expression to use for splitting.

Example of Regular Expression

Suppose we have a string that contains the names of cars separated by a dot.

const cars = "bmw.audi.mercedes";

We can use a regular expression to split the string into an array as follows:

const carsArray = cars.split(/\./);

The result will be an array of cars:

["bmw", "audi", "mercedes"]

Converting string to array using split() method

Splitting a string into an array is a common operation in JavaScript, and it can be done using the split() method. This method creates an array by separating a string into substrings, using a specified separator. The result is an array of strings, where each element is a substring of the original string that was separated by the separator.

Explanation of split() method

The split() method is a built-in function in JavaScript that is used to split a string into an array of substrings. The method takes a separator as a parameter, which can be a string or a regular expression, and returns an array of strings.

When the method is called on a string, the string is split into substrings whenever the separator is encountered. The substrings are then stored in an array, which is returned by the method.

Syntax of split() method

The syntax for using the split() method is as follows:

JAVASCRIPT

string.split(separator, limit)

Here, string is the string that you want to split, separator is the character or regular expression that you want to use as a separator, and limit is an optional parameter that specifies the maximum number of substrings to include in the array.

Example of split() method

Let’s say we have a string that contains a list of names, separated by commas:

JAVASCRIPT

const names = "John, Jane, Peter, Mary";

To split this string into an array of names, we can use the split() method as follows:

JAVASCRIPT

const nameArray = names.split(", ");

This will create an array of names, where each element is a substring of the original string that was separated by the , separator:

JAVASCRIPT

["John", "Jane", "Peter", "Mary"]

We can also use a regular expression as a separator. For example, let’s say we have a string that contains a list of words, separated by spaces:

JAVASCRIPT

const words = "apple banana orange";

To split this string into an array of words, we can use a regular expression as the separator:

JAVASCRIPT

const wordArray = words.split(/\s+/);

This will create an array of words, where each element is a substring of the original string that was separated by one or more spaces:

JAVASCRIPT

["apple", "banana", "orange"]

Converting string to array using Array.from() method

If you are looking to convert a string to an array in JavaScript, one of the methods you can use is Array.from(). This method returns a new array instance from an array-like or iterable object, which includes strings.

Explanation of 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. It allows you to create an array from a string without having to manually split the string into an array. This method can also be used to create a new array from other iterable objects such as a NodeList or a Map.

Syntax of Array.from() method

The syntax for using Array.from() method is as follows:

JAVASCRIPT

Array.from(arrayLike, mapFunction, thisValue);

The parameters of the Array.from() method are:

  • arrayLike: Required. An array-like or iterable object to convert to an array.
  • mapFunction: Optional. A function to call on each element in the array.
  • thisValue: Optional. A value to use as this when executing the mapFunction.

Example of Array.from() method

Here is an example of how to use the Array.from() method to convert a string to an array:

JAVASCRIPT

const str = "Hello World";
const arr = Array.from(str);
console.log(arr); // ["H", "e", "l", "l", "o", " ", "W", "o", "r", "l", "d"]

In this example, we pass the string “Hello World” to the Array.from() method, which returns a new array instance with each character of the string as an element in the array.

You can also use the mapFunction parameter to manipulate each element in the array. Here is an example:

JAVASCRIPT

const str = "Hello World";
const arr = Array.from(str, char => char.toUpperCase());
console.log(arr); // ["H", "E", "L", "L", "O", " ", "W", "O", "R", "L", "D"]

In this example, we pass the string “Hello World” to the Array.from() method and use the mapFunction parameter to convert each character to uppercase. The result is a new array instance with each character in uppercase.


Converting string to array using spread operator

The spread operator is a useful feature in JavaScript that allows us to expand an iterable object, such as an array or a string, into individual elements. In the case of converting a string to an array, the spread operator can be used to split the string into separate characters and store them in an array.

Explanation of spread operator

The spread operator is denoted by three consecutive dots (…) and can be used in various ways. In this context, it is used to spread a string into individual characters, which can then be stored in an array. The spread operator can also be used to combine arrays, copy arrays, and pass arguments to functions.

Syntax of spread operator

To use the spread operator to convert a string to an array, we simply need to place the spread operator before the string variable, as shown in the example below:

const myString = "Hello, world!";
const myArray = [...myString];

In this example, the string “Hello, world!” is stored in the variable myString, and the spread operator is used to convert it to an array of individual characters, which is stored in the variable myArray.

Example of spread operator

Here is an example of how the spread operator can be used to convert a string to an array and perform some operations on the resulting array:

const myString = "JavaScript is awesome!";
const myArray = [...myString];
console.log(myArray); // Output: ["J", "a", "v", "a", "S", "c", "r", "i", "p", "t", " ", "i", "s", " ", "a", "w", "e", "s", "o", "m", "e", "!"]
// Use Array.prototype.map() to convert each character to its corresponding ASCII code
const asciiArray = myArray.map(char => char.charCodeAt(0));
console.log(asciiArray); // Output: [74, 97, 118, 97, 83, 99, 114, 105, 112, 116, 32, 105, 115, 32, 97, 119, 101, 115, 111, 109, 101, 33]

In this example, the string “JavaScript is awesome!” is converted to an array using the spread operator, and then the Array.prototype.map() method is used to convert each character to its corresponding ASCII code. The resulting array of ASCII codes is stored in the asciiArray variable.


Converting string to array using Array.prototype.map() method

In JavaScript, the Array.prototype.map() method is used to create a new array by applying a function to each element of an existing array. This method can also be used to convert a string to an array, by mapping over each character in the string and returning an array of those characters.

Explanation of Array.prototype.map() method

The Array.prototype.map() method takes an input function as its argument, which is applied to each element of the array. The input function can take up to three arguments: the current element being processed, the index of that element, and the array being mapped over. The function returns a new value for each element, which is then added to the new array that is being created.

Syntax of Array.prototype.map() method

The syntax for using the Array.prototype.map() method to convert a string to an array is as follows:

let string = 'hello world';
let array = Array.prototype.map.call(string, function(char) {
return char;
});

In this example, the Array.prototype.map() method is being called on the string ‘hello world’, with a function that simply returns each character in the string. The resulting array will be [‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ‘, ‘w’, ‘o’, ‘r’, ‘l’, ‘d’].

Example of Array.prototype.map() method

Let’s take a closer look at how the Array.prototype.map() method can be used to convert a string to an array. Consider the following code:

let string = 'convert me to an array';
let array = Array.prototype.map.call(string, function(char) {
return char;
});
console.log(array);

In this example, the string ‘convert me to an array’ is being mapped over using the Array.prototype.map() method. The function being passed to the method simply returns each character in the string. The resulting array will be [‘c’, ‘o’, ‘n’, ‘v’, ‘e’, ‘r’, ‘t’, ‘ ‘, ‘m’, ‘e’, ‘ ‘, ‘t’, ‘o’, ‘ ‘, ‘a’, ‘n’, ‘ ‘, ‘a’, ‘r’, ‘r’, ‘a’, ‘y’].

Benefits of using Array.prototype.map() method

One benefit of using the Array.prototype.map() method to convert a string to an array is that it allows for more complex mapping functions to be used. For example, the function passed to the method could be used to convert each letter to its corresponding ASCII code or to remove certain characters from the string before mapping over it.

Another benefit is that the code is more concise and readable than other methods of converting a string to an array, such as using the split() method or regular expressions.


Converting string to array using regular expression

Regular expressions, also known as regex, are a powerful tool in programming used to match patterns in strings. In JavaScript, regular expressions are objects that can be used to perform various operations on strings such as searching, replacing, and parsing. In this section, we will explore how to use regular expressions to convert a string to an array.

Explanation of regular expression

A regular expression is a sequence of characters that define a search pattern. In JavaScript, regular expressions are defined using a pair of forward slashes (/pattern/). The pattern can consist of a combination of characters, symbols, and metacharacters, which have special meanings. For example, the dot (.) matches any character except for a newline, and the asterisk (*) matches zero or more occurrences of the preceding element.

Syntax of regular expression

To convert a string to an array using regular expression, we can use the split() method, which takes a as an argument. The syntax for the split() method is as follows:

string.split(regexp)

Where string is the string we want to convert to an array, and regexp is the regular expression we want to use to split the string. The split() method returns an array of substrings that are separated by the regular expression.

Example of regular expression

Let’s say we have a string “apple,banana,orange” that we want to convert to an array. We can use the regular expression /,/ to split the string at each comma. The code would look like this:

const fruitString = "apple,banana,orange";
const fruitArray = fruitString.split(/,/);
console.log(fruitArray);

The output would be:

["apple", "banana", "orange"]

In this example, the split() method splits the string at each comma and returns an array of substrings.

In conclusion, regular expressions can be a powerful tool in JavaScript when it comes to manipulating strings. By using the split() method with regular expressions, we can easily convert a string to an array. The regular expression syntax can be daunting at first, but with practice, it becomes easier to understand and use effectively.

Leave a Comment

Contact

3418 Emily Drive
Charlotte, SC 28217

+1 803-820-9654
About Us
Contact Us
Privacy Policy

Connect

Subscribe

Join our email list to receive the latest updates.