[英]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(*). 我有一个返回4条不同信息的过程,每条信息都用星号(*)分隔。 For example, the code will return something like:
例如,代码将返回如下内容:
Boy*15*Winter*New Years 男孩* 15 *冬天*新年
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? 有没有办法使用javascript做到这一点?
In ES6, you can do this trivially with destructuring : 在ES6中,您可以通过解构来轻松地做到这一点:
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: 在ES5中,您需要对其进行一点映射,但是可以非常轻松地创建对象:
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. 无论哪种方式,核心都是带有分隔符的
String.prototype.split
。
ES2015版本:
const [gender, age, favoriteSeason, favoriteHoliday] = yourVar.split('*');
Use split()
to break up the string: 使用
split()
分解字符串:
s = 'Boy*15*Winter*New Years';
a = s.split('*');
gender = s[0];
age = int(s[1])
favoriteSeason = s[2];
favoriteHoliday = s[3];
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.