Reputation: 95
I have string as:-
String -----> Result I need
1.25 acres ---> 1.25
125 acres ----> 125
1,25 sqft ----> 125
12,5 foot ----> 125
I am currently using :- .match(/\d+(\.\d+)?/)
but it is getting 1
for 1,25
and 12
for 12,5
Any suggestion?
Upvotes: 0
Views: 66
Reputation: 18611
Use
str.match(/\d+(?:[.,]\d+)*/g)
See regex proof.
EXPLANATION
NODE EXPLANATION
--------------------------------------------------------------------------------
\d+ digits (0-9) (1 or more times (matching
the most amount possible))
--------------------------------------------------------------------------------
(?: group, but do not capture (0 or more times
(matching the most amount possible)):
--------------------------------------------------------------------------------
[.,] any character of: '.', ','
--------------------------------------------------------------------------------
\d+ digits (0-9) (1 or more times (matching
the most amount possible))
--------------------------------------------------------------------------------
)* end of grouping
JavaScript code snippet:
const str = `1.25 acres
125 acres
1,25 sqft
12,5 foot`
console.log(str.match(/\d+(?:[.,]\d+)*/g))
Upvotes: 0
Reputation: 14171
You could also remove the first ,
you encounter and then use parseFloat
. Something like this:
parseFloat(str.replace(",",""))
Upvotes: 1