Tripati Subudhi
Tripati Subudhi

Reputation: 1691

How to get each value from a comma separated string in JavaScript?

Lets consider I have a string called

string s = "jpeg, jpg, gif, png";

So from this I need to get each one like, I can assign each extension to one var variable such as

var a = jpeg
var b = jpg
var c = gif
var d = png

Same way if I will add more extensions to the string then accordingly I will have to get all with same var variable.

Upvotes: 4

Views: 53534

Answers (8)

Cooler
Cooler

Reputation: 1

If you have a comma delimited string, which was the question, there's no need to split.

In this case response is a json object returned from a service via an ajax call. The json contains an element called tags which is itself a collection object which I put in a javaScript array.

var metaTags = new Array();
metaTags = response.Tags;

for (var tag in metaTags) {
  $("#divTagContainer").append("<div class='divTagItem'>" + metaTags[tag] + "</div>");
};

Upvotes: 0

Grooveek
Grooveek

Reputation: 10094

All you have to do is to use the javascript split method-

$(function(){
    var s = "jpeg, jpg, gif, png";
    var match = s.split(', ')
    console.log(match)
    for (var a in match)
    {
        var variable = match[a]
        console.log(variable)
    }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Upvotes: 16

Quentin
Quentin

Reputation: 943579

You can get an array with the split method:

"jpeg, jpg, gif, png".split(', ');

You can then loop over it to get the individual values.

Assigning the values in it to individual variables is, frankly, insane, but you could play with eval to achieve that.

Upvotes: 1

&#199;ağdaş
&#199;ağdaş

Reputation: 1023

lets consider you have a string like

**var** = s = "jpeg, jpg, gif, png";

split it with ',' and you have an array

var strArray = s.split(',')​

Upvotes: 0

Teun Zengerink
Teun Zengerink

Reputation: 4393

Use split:

var list = s.split(', ');

Upvotes: 0

Nitzan Tomer
Nitzan Tomer

Reputation: 164137

just do:

var arr = s.split(", ");

then you have an array of the values, iterate over that and do what ever

Upvotes: 0

Pranay Rana
Pranay Rana

Reputation: 176906

try Split function of javascript will do your task

string s = "jpeg, jpg, gif, png"; 
var arraylist = s.Split(", ") ;

point to Note : this provide you list of string i.e array of split string.......

Upvotes: 1

Tieson T.
Tieson T.

Reputation: 21191

s.Split(", ") should work.

Upvotes: 0

Related Questions