1

Hi All I have a string like this

var data='mobile,car,soap,room';

I am parsing from this string and making this string as comma sperated and pushing it into an array like this

var availableTags=[];
var str='';
for(i=0;i<data.length;i++)
{
  if(data[i]==',')
  {    
    availableTags .push(str);
    str='';
  }
  else
  {
    str +=data[i];
  }
}

But I am doing wrong as I cannot get the last value after comma... Now What I want to ask how can I come to know the next existence of , in my string that whether it exists or not. So that I can also include the last value.

I would also appreciate if someone guide me that how can I accomplish that same task some other way.

I want the string to be an array and it should look like this

  ["mobile","car","soap","room"]

5 Answers 5

4

you can use

var availableTags = data.split(",");

it will handle all the things. and will result in an array.

Sign up to request clarification or add additional context in comments.

Comments

3

You can use:

data.split(/,/)

See the split documentation.

Comments

1

After loop, you need to check value of str and add it too. It can contain the rest after last comma, or it can be empty in case comma was the last character in data.

But as other pointed, split is probably better way to do it.

Comments

1

As far as fixing your existing function, try adding the following after the for loop:

if (str != "")
   availableTags.push(str);

(When the loop ends str holds whatever came after the last comma.)

But like the other answers said, you can just use the array .split() method:

var availableTags = data.split(",");

Comments

0

You could append an extra comma on at the start:

data = data + ","

...

2 Comments

And in case the original string's last character was comma, then he'll get empty string as last element of resulting array
indeed. yes. that's true. (am I at 15 characters yet?)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.