How to convert string type value to array type in JavaScript?

Converting strings to arrays in JavaScript can be done using different methods depending on the string format. Here are the most common approaches.

Using JSON.parse() for JSON Strings

When you have a JSON-formatted string, use JSON.parse() to convert it to an array:

var customerDetails = '[{"name": "John", "countryName": "US"}, {"name": "David", "countryName": "AUS"}, {"name": "Bob", "countryName": "UK"}]';

console.log("Original string:", customerDetails);
console.log("Type:", typeof customerDetails);

var convertStringToArray = JSON.parse(customerDetails);
console.log("After converting to array:");
console.log(convertStringToArray);
console.log("Type:", typeof convertStringToArray);
Original string: [{"name": "John", "countryName": "US"}, {"name": "David", "countryName": "AUS"}, {"name": "Bob", "countryName": "UK"}]
Type: string
After converting to array:
[
  { name: 'John', countryName: 'US' },
  { name: 'David', countryName: 'AUS' },
  { name: 'Bob', countryName: 'UK' }
]
Type: object

Using split() for Regular Strings

For regular strings, use the split() method to convert to an array:

var fruits = "apple,banana,orange,grape";
var fruitsArray = fruits.split(",");

console.log("Original string:", fruits);
console.log("Array after split:", fruitsArray);
console.log("Array length:", fruitsArray.length);
Original string: apple,banana,orange,grape
Array after split: [ 'apple', 'banana', 'orange', 'grape' ]
Array length: 4

Using Array.from() for String Characters

To convert a string into an array of individual characters:

var text = "Hello";
var charArray = Array.from(text);

console.log("Original string:", text);
console.log("Character array:", charArray);
Original string: Hello
Character array: [ 'H', 'e', 'l', 'l', 'o' ]

Comparison of Methods

Method Use Case Input Example
JSON.parse() JSON-formatted strings '[1,2,3]' or '[{"key":"value"}]'
split() Delimited strings 'a,b,c' or 'word1 word2'
Array.from() Individual characters 'hello' ? ['h','e','l','l','o']

Conclusion

Use JSON.parse() for JSON strings, split() for delimited strings, and Array.from() for character arrays. Choose the method based on your string format.

Updated on: 2026-03-15T23:18:59+05:30

451 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements