我有一个字符串,希望根据类型将它们拆分为数组。 我可以像下面那样提取数字和浮点数,但是不能完成我的目标
var arr = "this is a string 5.86 x10‘9/l 1.90 7.00"
.match(/\d+\.\d+|\d+\b|\d+(?=\w)/g)
.map(function (v) {return v;});
console.log(arr);
arr = [5.86, 10, 9, 1.9, 7]
我想要甚至大块的字符串类型和混合像" x10'9 / l":
arr = ["this is a string", 5.86, "x10‘9/l", 1.9, 7]
有人能搞清楚吗?
答案 0 :(得分:0)
const result = [];
const str = "this is a string 5.86 x10‘9/l 1.90 7.00";
result.push(str.split(" ").reduce((acc, part) => isNaN(part) ? acc + " " + part : ((acc && result.push(acc)), result.push(+part), ""), ""));
答案 1 :(得分:0)
我想出了这个:
var arr = [];
var str = "this is a string 5.86 x10‘9/l 1.90 7.00";
arr.push(str.split(" ").reduce((acc, part) => isNaN(part) ? acc + " " + part : (arr.push(acc.trim(), +part), ""), ""));
var result = arr,
len = arr.length, i;
for(i = 0; i < len; i++ ) {
result[i] && result.push(result[i]); // copy non-empty values to the end of the array
}
result.splice(0 , len); // cut the array and leave only the non-empty values
console.log(result);