我在 textarea 中有 xml 内容,可以是以下形式,
<tag value="20.434" value1="-12.334" />
或者
20.434 -12.334
我希望能够提取每行的两个 float 。
最佳答案
您可以将正则表达式 /[+-]?\d+(\.\d+)?/g
与 String.match()
结合使用解析数字和 Array.map()
将它们变成花车:
var regex = /[+-]?\d+(\.\d+)?/g;
var str = '<tag value="20.434" value1="-12.334" />';
var floats = str.match(regex).map(function(v) { return parseFloat(v); });
console.log(floats);
var str2 = '20.434 -12.334';
var floats2 = str2.match(regex).map(function(v) { return parseFloat(v); });
console.log(floats2);
var strWithInt = "200px";
var ints = strWithInt.match(regex).map(function(v) { return parseFloat(v); });
console.log(ints);
关于javascript - 如何从javascript中的字符串中提取 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17374893/