n°19
Extraire un nombre décimal en Javascript
30 nov 2018
function extractFloat(element) {
element = element.toString();
var match = element.match(/-?\s*\d+(\.\d+)?/); // captures the first 0 or -0 or -0.0 match
if(match) {
return match[0].replace(/\s+/g, ''); // removes whitespaces (if any)
} else {
return false;
}
}
console.log(extractFloat("margin-top: - 66.67 px")); // -66.67
console.log(extractFloat("I ate 10 apples in the last 5 days")); // 10
console.log(extractFloat("2*a")); // 2
console.log(extractFloat(-5.0)); // -5