Reputation: 1
I have a process that returns 4 different pieces of information, each piece separated by an asterisk(*). For example, the code will return something like:
Boy*15*Winter*New Years
I want to split this string into individual and assign values to each piece.
So something like this:
var gender = Boy
var age = 15
var favoriteSeason = Winter
var favoriteHoliday = New Years
But I do not want those variables hard-coded.
Is there a way to do this using javascript?
Upvotes: 0
Views: 31
Reputation: 1748
ES2015 version:
const [gender, age, favoriteSeason, favoriteHoliday] = yourVar.split('*');
Upvotes: 1
Reputation: 48247
In ES6, you can do this trivially with destructuring:
const [gender, age, favoriteSeason, favoriteHoliday] = 'Boy*15*Winter*New Years'.split('*');
In ES5, you need to map it a little bit, but can create objects pretty easily:
var chunks = 'Boy*15*Winter*New Years'.split('*');
return {
gender: chunks[0],
age: chunks[1],
favoriteSeason: chunks[2],
favoriteHoliday: chunks[3],
};
Either way, the core is String.prototype.split
with your separator.
Upvotes: 1
Reputation: 102174
var str = "Boy*15*Winter*New Years";
var array = str.split("*");
var gender = array[0];
var age = array[1];
var favoriteSeason = array[2];
var favoriteHoliday = array[3];
console.log(gender, age, favoriteSeason, favoriteHoliday)
Upvotes: 0
Reputation: 24557
Use split()
to break up the string:
s = 'Boy*15*Winter*New Years';
a = s.split('*');
gender = s[0];
age = int(s[1])
favoriteSeason = s[2];
favoriteHoliday = s[3];
Upvotes: 0