在一串文本中找到 integers/floats/strings 并放入数组
Find integers/floats/strings in a string of text and put in array
我有一个字符串,想根据类型将它们拆分成一个数组。
我可以像下面那样提取数字和浮点数,但还没有完成我的目标
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]
有人能猜出来吗?
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), ""), ""));
我想到了这个:
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);
我有一个字符串,想根据类型将它们拆分成一个数组。 我可以像下面那样提取数字和浮点数,但还没有完成我的目标
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]
有人能猜出来吗?
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), ""), ""));
我想到了这个:
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);