Javascript 字符串的 JQuery 过滤器编号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4460595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:30:51  来源:igfitidea点击:

JQuery Filter Numbers Of A String

javascriptjquerystring

提问by Tomkay

How do you filter only the numbers of a string?

如何仅过滤字符串的数字?

Example Pseudo Code:
number = $("thumb32").filternumbers()
number = 32

回答by Jonathon Bolster

You don't need jQuery for this - just plain old JavaScript regex replacement

你不需要 jQuery - 只是简单的旧 JavaScript正则表达式替换

var number = yourstring.replace(/[^0-9]/g, '')

var number = yourstring.replace(/[^0-9]/g, '')

This will get rid of anything that's not [0-9]

这将摆脱任何不是 [0-9]

Edit: Here's a small function to extract all the numbers (as actual numbers) from an input string. It's not an exhaustive expression but will be a good start for anyone needing.

编辑:这是一个从输入字符串中提取所有数字(作为实际数字)的小函数。这不是一个详尽的表达,但对于任何需要的人来说都是一个好的开始。

function getNumbers(inputString){
    var regex=/\d+\.\d+|\.\d+|\d+/g, 
        results = [],
        n;

    while(n = regex.exec(inputString)) {
        results.push(parseFloat(n[0]));
    }

    return results;
}

var data = "123.45,34 and 57. Maybe add a 45.824 with 0.32 and .56"
console.log(getNumbers(data));
// [123.45, 34, 57, 45.824, 0.32, 0.56];

回答by Pointy

Not really jQuery at all:

根本不是真正的jQuery:

number = number.replace(/\D/g, '');

That regular expression, /\D/g, matches any non-digit. Thus the call to .replace()replaces all non-digits (all of them, thanks to "g") with the empty string.

该正则表达式/\D/g匹配任何非数字。因此,调用以.replace()空字符串替换所有非数字(所有这些,感谢“g”)。

edit— if you want an actual *numbervalue, you can use parseInt()after removing the non-digits from the string:

编辑——如果你想要一个实际的 *数字值,你可以parseInt()在从字符串中删除非数字后使用:

var number = "number32"; // a string
number = number.replace(/\D/g, ''); // a string of only digits, or the empty string
number = parseInt(number, 10); // now it's a numeric value

If the original string may have no digits at all, you'll get the numeric non-value NaNfrom parseIntin that case, which may be as good as anything.

如果原始字符串可能根本没有数字,你会得到的数字非价值NaNparseInt在这种情况下,这可能是一样好东西。