-2

I'm working on google maps, which is retuning distance in string like 1,230.6 km. From this I wanted to extract the floating number 1230.6.

Below is what I tried

var t = '1,234.04 km';
var a = t.replace(/[^0-9]/g, '') // 123404

parseFloat(t) // 1

How do I fix this with Regex ? Please guide

3 Answers3

1

You can do the following,

var t = '1,234.04 km';
var a = t.replace(/[^0-9.]/g, '')
    
console.log(parseFloat(a) )
Md Sabbir Alam
  • 4,937
  • 3
  • 15
  • 30
1

You can add . in your Regex:

var t = '1,234.04 km';
var a = t.replace(/[^0-9.]/g, '') // 1234.04

parseFloat(a) // 1234.04
KValium
  • 111
  • 1
  • 11
0
let t = '1,234.04 km'.split(',').join('');
var regex = /[+-]?\d+(\.\d+)?/g;
var floats = t.match(regex).map(function(v) { return parseFloat(v); });
console.log(+floats);
imh1j4l
  • 95
  • 5
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. – ucMedia Jan 12 '21 at 09:59