这是诀窍,你可以先用':'分割字符串,然后对于从第二个元素开始的每个组件,得到最后一部分用空格分隔并假设这是下一个键值对的名称,这是我的尝试:
var string = "Org nr: 9 670220-5458 Firma: Shamel Taxi Kommun: Botkyrka Postadress: Grytstigen 84, 147 52 TUMBA, Verksamhet: Bolaget ska bedriva taxiverksamhet. Innehavare: 19670220-5458 Fathalla, Shamel Said, Grytstigen 84, 147 52 TUMBA,;"
splited = string.split(':');
list = [splited[0]]
for (x in splited) {
if (x == 0) continue;
var t = splited[x].split(' ');
list.push(t.slice(0, t.length - 1).join(' ').trim());
list.push(t[t.length - 1].trim());
}
result = {}
for (var i = 0; i < list.length - 1;) {
result[list[i]] = list[i + 1];
i += 2;
}
console.log(result);
这是结果
Firma: "Shamel Taxi"
Innehavare: "19670220-5458 Fathalla, Shamel Said, Grytstigen 84, 147 52"
Kommun: "Botkyrka"
Org nr: "9 670220-5458"
Postadress: "Grytstigen 84, 147 52 TUMBA,"
Verksamhet: "Bolaget ska bedriva taxiverksamhet."
同样,您可以使用此代码,由于输入太随机,这是我能给您的最好的。