如何在javascript中从字符串中提取浮点数 [英] how to extract floating numbers from strings in javascript

查看:141
本文介绍了如何在javascript中从字符串中提取浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

20.434 -12.334

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

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

推荐答案

你可以使用正则表达式 / [+ - ]?\d +(\。\ \\ d +)?/ g 一起使用 String.match() 解析数字和 Array.map() 将它们变成浮点数:

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

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中从字符串中提取浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆