JQuery过滤字符串的数字 [英] JQuery Filter Numbers Of A String
本文介绍了JQuery过滤字符串的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何仅过滤字符串的数字?
How do you filter only the numbers of a string?
Example Pseudo Code:
number = $("thumb32").filternumbers()
number = 32
推荐答案
你不需要jQuery - 只需普通的旧JavaScript 正则表达式替换
You don't need jQuery for this - just plain old JavaScript regex replacement
var number = yourstring.replace(/ [^ 0-9] / g,'')
这将消除任何不是[0-9]
This will get rid of anything that's not [0-9]
编辑:这是一个小函数来提取所有输入字符串中的数字(作为实际数字)。这不是一个详尽的表达,但对于任何需要的人来说都是一个良好的开端。
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];
这篇关于JQuery过滤字符串的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文