How to extract floating numbers from strings in javascript

I have xml content in textarea, which may look like

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

or

 20.434 -12.334 

I want to be able to extract two floating numbers in a string.

+4
source share
3 answers

You can use the regular expression / /[+-]?\d+(\.\d+)?/g - String.match() /[+-]?\d+(\.\d+)?/g in combination with String.match() to parse 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 the demo code here.

+20
source

You are going to use parseFloat as soon as you figure out how to extract numbers from your text ... How you extract these numbers depends entirely on what the text is. Most likely, you will divide all the text into \ s, and then delete all characters that are not numbers and dots. This should leave you with floats ... although again it is impossible to say without seeing what the surrounding text looks like.

EDIT: Okay, now that you have changed your question, the answer is that you just take the attributes named value and value1 and run parse float over what's in them. If your text area contains this XML, you need to parse the XML first to get attributes as objects.

+2
source

You can always load a string in 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 best route.

+1
source

Source: https://habr.com/ru/post/1488791/


All Articles