Skip to content

JavaScript string to array | Convert

  • by

Using the split() method you can convert string to array in JavaScript. This method splits a string into an array of substrings and returns the new array.

string.split(delimiter/separator, limit)

This method does not change the original string.

JavaScript string to array

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>
    let text = "How are you doing today?";
    const myArray = text.split(" ");

    console.log(myArray)
    console.log(myArray[1]);

  </script>
</body>
</html>

Output:

JavaScript string to array

You can change the delimiter accordingly can help you convert strings to arrays in JavaScript. Let’s look at a case where "," is a delimiter.

let str1 = 'JavaScript,Python,C++,PHP';

const split_string = str1.split(",");
console.log(split_string)

Output: [“JavaScript”, “Python”, “C++”, “PHP”]

Another way to convert a string to an array is to use the Array.from() method. This method creates a new array from an iterable object, where each element of the array corresponds to an element of the iterable.

let str = "Hello, world!";
let arr = Array.from(str);
console.log(arr); // Output: ["H", "e", "l", "l", "o", ",", " ", "w", "o", "r", "l", "d", "!"]

Do comment if you have any doubts or suggestions on this JS string topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading