好吧,您可以自己做,也可以懒惰并使用以下代码:
var string = "1 book at 12.49 1 music CD at 14.99 1 chocolate bar at 0.85";
var data = getArray(string);
console.debug(data);
function getArray(string){
//prepare the string
//adding terminators (";")
string = string.replace(/(at) ([0-9]*).([0-9]*)/g,"$1 $2.$3;");
string = string.replace(/; /g,";"); //remove whitespace after terminators
string = string.substring(0,string.length-1); //remove last terminator
var split = string.split(";"); //split it up
var data = new Array();
//loop through objects
for(var i=0;i<split.length;i++){
data[i] = new Array();
var subData = split[i].split(" ");
data[i]['count'] = subData[0]; //0 is count
data[i]['price'] = subData[subData.length-1]; //last is price
data[i]['article'] = "";
for(var j=1;j<subData.length-2;j++){ //in between is the name (minus the "at")
data[i]['article'] += subData[j] + " ";
}
}
return data //and done
}
jsFiddle:http: //jsfiddle.net/3sNBJ/1/
...我敢打赌会有更好的解决方案,但我对正则表达式也不是很好...
[编辑] ...哦,导入也是需要的值...嗯,http://jsfiddle.net/3sNBJ/3/
[edit2] ...现在使用 ui:http: //jsfiddle.net/3sNBJ/5/