How to extract a float from a string in JavaScript

1 Answer

0 votes
const text = "The price is 148.95 dollars";
const floatRegex = /[-+]?\d*\.\d+|\d+/;
const match = text.match(floatRegex);

if (match) {
    const number = parseFloat(match[0]);
    console.log("Extracted float:", number);
}


 
/*
run:
     
Extracted float: 148.95
      
*/

 



answered Jul 29 by avibootz
...