Reputation:
Let's say I have this :
var colors = 'Red,Blue,Green,Orange,White,Brown';
I tried to parse it to get all the colors which means :
color1='Red';
color2='Blue';
[...]
I used to use the matches()
and then put a comma since the colors are separated by commas so I put ',', but the result is not what I've expected... Is there any fast way to do it?
Upvotes: 3
Views: 95
Reputation: 4166
You can use below code:
String [] stringParts = myString.split(":");
Upvotes: -1
Reputation: 8920
If you dont mind to have it on the global object:
'Red,Blue,Green,Orange,White,Brown'.split(',').forEach(function(color, index ){
window['color' + index] = color;
});
Upvotes: 4
Reputation: 207537
To match it with a regular expression you just need to use \w+
which matches any of the following characters A-Z a-z 0-9 _
.
var colors = 'Red,Blue,Green,Orange,White,Brown';
var matches = colors.match(/\w+/g);
console.log(matches[0]);
If you are worried about matching the numbers and underscore, you can always just use /[a-z]+/gi
Upvotes: 2
Reputation: 20646
Is there any fast way to do it?
Yep, I recommend you to use split()
As the docs says :
The split() method is used to split a string into an array of substrings, and returns the new array.
Tip: If an empty string ("") is used as the separator, the string is split between each character.
Note: The split() method does not change the original string.
So you could get the same of your colors doing something like this :
var colors = 'Red,Blue,Green,Orange,White,Brown'.split(','); //use .split() to split the character you want to.
var color1 = colors[0];
var color2 = colors[1];
var color3 = colors[2];
[...]
alert("Color 1 = " +color1 + "\n"+ "Color 2 = " + color2);
Now you could do some logic to know the items that are on your var colors
or whatever you want.
Hope it helps.
Upvotes: 5