js提取字符串中的数字

262 阅读1分钟
  • 数字在前,非数字在后:parseFloat函数
let num = "2.3aa"  
parseFloat(num) // 2.3
  • 只包含一个数字的字符串
let num = "±12.2",num1 = "±1.2aa"
num.replace(/[^\d]/g,'') // 122
num1.replace(/[^.\d]/g,'') // 1.2
  • 包含多个数字的字符串
let num = "a12.2,b:3.4g",num1 = "89.5+7*5-9/3.0+8.5"
num.match(/\d+(\.\d+)?/g) // ["12.2","3.4"]
num1.match(/\d+(\.\d+)?/g) // ["89.5","7","5","9","3.0","8.5"]