How do you filter only the numbers of a string?
Example Pseudo Code:
number = $("thumb32").filternumbers()
number = 32
You don't need jQuery for this - just plain old JavaScript regex replacement
var number = yourstring.replace(/[^0-9]/g, '')
This will get rid of anything that's not [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];
Not really jQuery at all:
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.
edit — if you want an actual *number value, you can use parseInt()
after removing the non-digits from the string:
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 NaN
from parseInt
in that case, which may be as good as anything.
精彩评论