0

I have a string like this:

var string = ' [United States] [Canada] [India] ';

I want to do a for loop and add each of the countries into an array in Javascript or Jquery, something like this:

var countryArray = new Array();
for ( each country in string AS country) {
  countryArray.push(country);      
}

I'm not sure how I would make a foreach loop out of a string like that.

2
  • You can get that array with a regular expression... Commented Apr 7, 2012 at 21:09
  • Did you try splitting the string with "[U] [C] [I]".split(' '); ? Commented Apr 7, 2012 at 21:10

3 Answers 3

5

Here:

var arr = str.match(/\[.+?\]/g).map(function (s) { return s.slice(1, -1); });

Live demo: http://jsfiddle.net/bWC9F/

There's probably a better way to do it, though...

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

Comments

2

I would do it like this

string.match(/\[(.*?)\]/g).map(function(inp){return inp.substring(1, inp.length - 1)})

wow. exact same thing

1 Comment

Yea, pretty much :) I think it's possible to make the match method return the strings without the brackets, but I don't know how to do that....
2

split()?

var string = ' [United States] [Canada] [India] ';
var arr = string.split(/([[^[]*])/ );

alert(arr);

1 Comment

This won't work, as this will display the output like this - [United States,], [Canada,], [India,],. Please check here- jsfiddle.net/4yHp5

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.