JavaScript 从字符串中提取数字

JavaScript 从字符串中提取数字

在这篇文章中,我们将学习如何从给定的字符串中提取数字。

提取字符串中的数字的方法:

  • 使用JavaScript的match()方法和正则表达式
  • 使用JavaScript的reduce()方法和展开运算符
  • 使用JavaScript的replace()方法和正则表达式

方法1:使用JavaScript的match方法和正则表达式

可以通过使用match方法和正则表达式将字符串中的数字提取为数字数组。该函数接受一个正则表达式作为参数,并从字符串中提取数字。提取数字的正则表达式为(/(\d+)/)。

示例1: 这个示例使用match()函数和正则表达式从字符串中提取数字。

// Function to extract numbers
function myGeeks() {
 
    // Input string
    let str = "jhkj7682834";
    console.log(str)
 
    // Using match with regEx
    let matches = str.match(/(\d+)/);
     
    // Display output if number extracted
    if (matches) {
        console.log(matches[0]);
    }
}
 
// Function call
myGeeks();

输出

jhkj7682834
7682834

示例2: 此示例使用match()函数从字符串中提取数字。

// Function to extract numbers
function myGeeks() {
 
    // Input string
    let str = "foo35bar5jhkj88";
    console.log(str)
 
    // Using match with regEx
    let matches = str.match(/\d+/g);
     
    // Display output if number extracted
    if (matches) {
        console.log(matches[0] +', '+ matches[1]+', ' + matches[2]);
    }
}
 
// Function call
myGeeks();

输出

foo35bar5jhkj88
35, 5, 88

方法2:使用JavaScript的reduce()方法和spread操作符

Javascript的 arr.reduce() 方法用于将数组减少为单个值,并对数组的每个值(从左到右)执行提供的函数,函数的返回值存储在累加器中。

语法:

array.reduce( function(total, currentValue, currentIndex, arr),   
initialValue )  

示例: 这个示例使用扩展运算符将其转换为数组,然后使用reduce方法从字符串中提取所有数字。

// Function to extract numbers
function myGeeks() {
    // Input string
    let str = "jhkj7682834";
    let c = "0123456789";
    console.log(str);
    function check(x) {
        return c.includes(x) ? true : false;
    }
    let matches = [...str].reduce(
        (x, y) => (check(y) ? x + y : x),"");
 
    // Display output if number extracted
    if (matches) {
        console.log(matches);
    }
}
 
// Function call
myGeeks();

输出

jhkj7682834
7682834

方法3:使用JavaScript的replace()方法和正则表达式

string.replace() 是JavaScript中的内置方法,用于用另一个字符串或正则表达式替换给定字符串的一部分。原始字符串将保持不变。
语法:

str.replace(value1, value2)  

示例: 在这个示例中,我们将使用 Javascript 的 replace() 方法和正则表达式从给定的字符串中提取出数字。

// Function to extract numbers
function myGeeks() {
    // Input string
    let str = "jhkj7682834";
    console.log(str);
 
    // Using match with regEx
    let matches = str.replace(/[^0-9]/g, "");
 
    // Display output if number extracted
    if (matches) {
        console.log(matches);
    }
}
 
// Function call
myGeeks();

输出

jhkj7682834
7682834 

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程