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.
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.
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.
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.
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:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With