[英]Find integers/floats/strings in a string of text and put in array
I have a string and want split them in an array based on type. 我有一个字符串,想根据类型将它们拆分为一个数组。 I can extract numbers and floats like below, but is not complete to my goal
我可以像下面那样提取数字和浮点数,但是并没有达到我的目标
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]
I would like have even chunk of string type and mixed like "x10'9/l": 我什至希望有字符串类型的大块并且像“ x10'9 / l”那样混合:
arr = ["this is a string", 5.86, "x10‘9/l", 1.9, 7]
can someone figure out? 有人可以找出来吗?
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), ""), ""));
I came up with this: 我想出了这个:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.