javascriptregex

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.


Solution

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

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