正则表达式取字符串中的数字

字符串中只含有一个整型数值的字符串,直接使用正则表达式将数字的字符删除掉就行

let str = "你好22世纪"

let num = str.replace(/[^\d]/g, '')  //num: 22

字符串中只含有多个数值

let str = "你好89.5我是7*5-9/3.0+8.5"
let num1 = str.match(/\d+(\.\d+)?/g) 
console.log(num1)  // ["89.5", "7", "5", "9", "3.0", "8.5"]
let num2 = str.match(/[^\d\.]/g)
console.log(num2)  // ['你好',"我是", "*", "-", "/", "+"]

猜你喜欢

转载自blog.csdn.net/CSDN_33901573/article/details/126268205
今日推荐