0

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?

1
  • Split the string on the asterisk and then map that array to an array that contains the order of data. ['gender', 'age', ...] in this case. Commented Aug 3, 2016 at 15:07

4 Answers 4

1

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.

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

Comments

1

ES2015 version:

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

Comments

0

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];

Comments

0

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)

Comments

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.