Brian Marcotte
Brian Marcotte

Reputation: 1

How can I separate a string using JavaScript and assign values to each piece of the String?

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

Answers (4)

Maxx
Maxx

Reputation: 1748

ES2015 version:

const [gender, age, favoriteSeason, favoriteHoliday] = yourVar.split('*');

Upvotes: 1

ssube
ssube

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

Gerardo Furtado
Gerardo Furtado

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

r3mainer
r3mainer

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

Related Questions