JavaScript 从字符串中删除所有非数字字符
在本文中,我们将从字符串中删除所有非数字字符。为了从字符串中删除所有非数字字符,我们使用了 replace() 函数。
从字符串中删除所有非数字字符的方法:
- 使用JavaScript的replace()函数
- 使用JavaScript的正则表达式
- 使用JavaScript的str.split() 和 array.filter() 方法
方法1:使用JavaScript的replace()函数
该函数搜索字符串中特定的值或正则表达式,并返回替换后的新字符串。
语法:
string.replace( searchVal, newValue )
示例 1: 此示例从字符串 ‘1Gee2ksFor345Geeks6’ 中删除所有非数字字符,借助 RegExp 。
// Input string
let str = "1Gee2ksFor345Geeks6";
console.log(str);
// Function to get non-numeric numbers
// and display output
function stripValues() {
console.log(str.replace(/\D/g, ""));
}
// Function call
stripValues();
输出
1Gee2ksFor345Geeks6
123456
方法2:使用JavaScript正则表达式和match方法
正则表达式是由字符序列组成的搜索模式。搜索模式可以用于文本搜索和替换操作。
语法:
let patt = /GeeksforGeeks/i;
示例: 此示例从字符串 ‘1Gee2ksFor345.Gee67ks89’ 中删除所有非数字字符,使用 RegExp 来帮助实现。此示例保留浮点数。
// Input string
let str = "1Gee2ksFor345Geeks6";
console.log(str);
// Function to get non-numeric numbers
// and display output
function stripValues() {
console.log((str.match(/[^\d.-]/g,"") || []).join(""));
}
// Function call
stripValues();
输出
1Gee2ksFor345Geeks6
GeeksForGeeks
方法3:使用JavaScript的str.split()和array.filter()方法
示例: 在本示例中,我们将使用str.split()和array.filter()方法
// Input string
let str = "1Gee2ksFor345Geeks6";
console.log(str);
// Function to get non-numeric numbers
// and display output
function stripValues() {
console.log( str.split("").filter(char => isNaN(parseInt(char))).join(""));
}
// Function call
stripValues();
输出
1Gee2ksFor345Geeks6
GeeksForGeeks
极客教程