How to convert string to array in JavaScript

Hi all,
Today we discuss related to important topic related to string to array convertion using javascript. When I’m doing my project I face this problem, get the values from api url using ajax, the success data is string then I can’t display the values in dropdown list. Based on this problem I found the solution: first convert the success data (string) to array values.

First we move two important topics related to this article.
The JSON.stringify and JSON.parse are very important in string to array conversion.

JSON.stringify in JavaScript

We use the Json.stringify in JavaScript to convert JavaScript object into a string.
When sending data to a web server, the data has to be a string.

Stringify a JavaScript Array

Suppose we have an variable in javascript. The variable values are array but we want to convert this array into string.

 var a = ["Kerala","Haryana","Delhi","Chandigarh","West Bengal","Uthar Pradesh"];

Use the JavaScript function JSON.stringify() to convert it into a string.

 var b=JSON.stringify(a);

The output is like:

[“Kerala”,”Haryana”,”Delhi”,”Chandigarh”,”West Bengal”,”Uthar Pradesh”]

Stringify a JavaScript Object

Suppose we have an object in javascript.

 var a = {"State":"Kerala", "District":"Ernakulam", "Pincode":674091};

Use the JavaScript function JSON.stringify() to convert it into a string.

var b = JSON.stringify(a);

The output is like:

{“State”:”Kerala”, “District”:”Ernakulam”, “Pincode”:674091}


When we receive the data from server, the data is always string.
We use JSON.parse() in javascript the string data convert to as array.

var a = JSON.parse('{ "name":"Priya", "age":13, "city":"Ernakulam"}');
document.getElementById("demo").innerHTML = + ", " + a.age;

The output like:


String to Array in Javascript

Next we move to how to convert the array value to string and then it convert to array and finally the data is displayed in dropdown list. Are you confused?. Everybody think as normal why we convert array to string then to array, easily we can convert string array value into dropdown list. That’s cool. We can consider first array to string value or direct string values here I consider array value and convert this array values to string and then convert to array and display it into dropdownlist. This process is mainly used in ajax success result. If the value is string then we use this operation.

Full Code

Leave a Reply

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