javascript 如何从javascript中的字符串中提取浮点数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17374893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:05:00  来源:igfitidea点击:

how to extract floating numbers from strings in javascript

javascriptregex

提问by gizgok

I have xml content in textarea which can be of the form,

我在 textarea 中有 xml 内容,它可以是以下形式,

<tag value="20.434" value1="-12.334" /> 

Or

或者

20.434 -12.334

I want to be able to extract the two floating numbers per line.

我希望能够提取每行的两个浮点数。

回答by acdcjunior

You can use the regex /[+-]?\d+(\.\d+)?/gin conjunction with String.match()to parse the numbers and Array.map()to turn them into floats:

您可以/[+-]?\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);

See demo code here.

在此处查看演示代码。

回答by Mataniko

You can always load the string into jQuery and get the attributes:

您始终可以将字符串加载到 jQuery 中并获取属性:

$('<tag value="20.434" value1="-12.334" />').attr('value')
$('<tag value="20.434" value1="-12.334" />').attr('value1')

In your case regex is probably the better route.

在您的情况下,正则表达式可能是更好的途径。

回答by Yevgeny Simkin

You're going to use parseFloat once you figure out how to extract the numbers from between your text... How you extract those numbers depends entirely on what that text is. Most likely you'll split the entire text on a \s and then remove all the characters that aren't numbers and dots. That should leave you with the floats... though again, impossible to say without seeing what the surrounding text looks like.

一旦您弄清楚如何从文本之间提取数字,您将使用 parseFloat ……如何提取这些数字完全取决于该文本是什么。很可能您将在 \s 上拆分整个文本,然后删除所有不是数字和点的字符。那应该让你留下浮点数......尽管如此,如果不看看周围的文字是什么样子就不可能说出来。

EDIT: Ok now that you've changed your question the answer is that you'll simply grab the attributes named value and value1 and run parse float on what's in them. If your text area contains this XML you'll need to parse the XML first to get the attributes as objects.

编辑:好的,现在你已经改变了你的问题,答案是你只需获取名为 value 和 value1 的属性,并对它们中的内容运行 parse float 。如果您的文本区域包含此 XML,您将需要首先解析 XML 以获取作为对象的属性。