Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to extract floating numbers from strings in javascript

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

<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.

like image 900
gizgok Avatar asked Jun 28 '13 23:06

gizgok


People also ask

How to extract float numbers from a string in Java?

In this tutorial, we will look at how to extract float numbers from a string in Java. To do this we will use a regular expression to match and find float values in a string. We will use pattern matching to find float numbers from the string. Given below is the pattern that you can use.

How to extract number from string in JavaScript?

The number from a string in javascript can be extracted into an array of numbers by using the match method. This function takes a regular expression as an argument and extracts the number from the string. Regular expression for extracting a number is (/(\d+)/). Example 1: This example uses match() function to extract number from string.

How to convert a string to a floating number in JavaScript?

Javascript has provided a method called parseFloat () to convert a string into a floating poin t number. Floating numbers are nothing but decimals. We also have another method called parseInt () to do the same task but it will not deal with decimals. It returns only integers.

How to parse a string into a float value?

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:


2 Answers

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);

See demo code here.

like image 188
acdcjunior Avatar answered Oct 05 '22 10:10

acdcjunior


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

$('<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.

like image 44
Mataniko Avatar answered Oct 05 '22 09:10

Mataniko