JavaScript中可以使用正则表达式来在字符串中提取数字。例如,下面的代码将在字符串 "The cost is $120.50" 中提取出数字:
let str = "The cost is $120.50";
let result = str.match(/d+(.d+)?/g);
console.log(result); // Output: ["120.50"]
在这里,d匹配任意数字,而+表示匹配一个或多个数字。.匹配小数点,|是或的意思,最后在后面加上g 代表全局匹配,就会返回所有匹配的值,而不是第一个匹配的值。
如果你只需要提取一次的话可以使用str.match(/d+(.d+)?/g)[0]
let str = "The cost is $120.50";
let result = str.match(/d+(.d+)?/g)[0];
console.log(result); // Output: "120.50"