我有一个字符串:
Pizza(food), Orange(fruit), Sandwich(food), lettuce(vegetable), Apple(fruit)
,Burger(food)
我想将字符串填充为:
food: Pizza, Sandwich, Burger
fruit: Orange, Apple
Vegetable: lettuce
答案 0 :(得分:3)
性交
var str = "Pizza(food), Orange(fruit), Sandwich(food), lettuce(vegetable), Apple(fruit) ,Burger(food)";
var obj = str.split(',').reduce(function(acc, token){
token = token.trim().split(/\(|\)/).filter(Boolean);
return (acc[token[1]]||(acc[token[1]] = [])).push(token[0]), acc;
}, {});
var newStr = Object.keys(obj).map(function(key){
return key + ': ' + obj[key].join(', ');
}).join('\n');
答案 1 :(得分:1)
更多Hardcore:
var s = "Pizza(food), Orange(fruit), Sandwich(food), lettuce(vegetable), Apple(fruit) ,Burger(food)";
var result = s.split(",");
console.log(result);
var s1 = "food : ";
var s2 = "fruit : ";
var s3 = "vegetable : ";
for (var i = 0; i < result.length; i++){
var item = result[i].replace(/\(/,"-").replace(/\)/,"").split("-");
switch(item[1]){
case "food":
s1 += item[0] + " ";
break;
case "fruit":
s2 += item[0] + " ";
break;
case "vegetable":
s3 += item[0] + " ";
break;
}
}
console.log(s1+"\n"+s2+"\n"+s3);