如何使用JavaScript分隔字符串并为每个字符串赋值?

时间:2016-08-03 15:05:07

标签: javascript html string split

我有一个流程返回4条不同的信息,每条信息用星号(*)分隔。例如,代码将返回如下内容:

男孩* 15 *冬季*新年

我想将此字符串拆分为单独的字符串,并为每个字符分配值 所以像这样:

$stmt = $db->prepare("UPDATE reservations SET name = :name, start = :start, end = :end, room_id = :room, status = :status, paid = :paid, customer = :customer, name_ship = :name_ship, equipment = :equipment, port = :port, ETA = :ETA, ETD = :ETD, service_id = :service_id, service_classification = :service_classification, job = :job WHERE id = :id");

但我不希望这些变量硬编码。

有没有办法用javascript做到这一点?

4 个答案:

答案 0 :(得分:1)

在ES6中,您可以使用destructuring

轻松完成此操作
const [gender, age, favoriteSeason, favoriteHoliday] = 'Boy*15*Winter*New Years'.split('*');

在ES5中,您需要稍微映射一下,但可以非常轻松地创建对象:

var chunks = 'Boy*15*Winter*New Years'.split('*');
return {
  gender: chunks[0],
  age: chunks[1],
  favoriteSeason: chunks[2],
  favoriteHoliday: chunks[3],
};

无论哪种方式,核心都是String.prototype.split与您的分隔符。

答案 1 :(得分:1)

ES2015版本:

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

答案 2 :(得分:0)

使用split()分解字符串:

s = 'Boy*15*Winter*New Years';
a = s.split('*');
gender = s[0];
age = int(s[1])
favoriteSeason = s[2];
favoriteHoliday = s[3];

答案 3 :(得分: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)