📜  js 只获取数字 - Javascript (1)

📅  最后修改于: 2023-12-03 15:32:22.759000             🧑  作者: Mango

JS 只获取数字

在JavaScript中,如果你需要从字符串中仅获取数字,有几种方法可以做到。

1. 使用parseInt函数

parseInt函数允许我们从一个字符串中获取数字。它需要一个字符串作为参数,并返回整数。

const str = "123abc";
const num = parseInt(str);
console.log(num); // Output: 123

需要注意的是,如果字符串的开头不是数字,则parseInt函数将返回NaN。

const str = "abc123";
const num = parseInt(str);
console.log(num); // Output: NaN
2. 使用正则表达式

另一种方法是使用正则表达式。我们可以使用正则表达式来匹配数字,并提取它们。以下是一个示例:

const str = "abc123";
const num = str.match(/\d+/);
console.log(num); // Output: ["123"]

在上面的代码中,\d+是一个正则表达式,它匹配一个或多个数字。当我们调用match函数时,它将匹配的数字存储在数组中,并返回该数组。

请注意,在字符串中有多个数字时,这种方法只会匹配第一个数字。如果你想获取所有数字,你可以使用全局标志g。

const str = "123abc456def789ghi";
const num = str.match(/\d+/g);
console.log(num); // Output: ["123", "456", "789"]
3. 使用正则表达式和map函数

如果你需要从数组中获取数字,你可以使用map函数和正则表达式。

const arr = ["123abc", "456def", "789ghi"];
const nums = arr.map(str => str.match(/\d+/)[0]);
console.log(nums); // Output: ["123", "456", "789"]

在上面的代码中,我们使用map函数迭代数组,并从每个字符串中提取数字。由于match函数返回数组,我们需要使用[0]来获取第一个数字。

这是三种获取数字的方法,可以根据你的需求选择其中之一。