Skip to content Skip to sidebar Skip to footer

Jquery Filter Numbers Of A String

How do you filter only the numbers of a string? Example Pseudo Code: number = $('thumb32').filternumbers() number = 32

Solution 1:

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.

functiongetNumbers(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];

Solution 2:

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:

varnumber = "number32"; // a stringnumber = number.replace(/\D/g, ''); // a string of only digits, or the empty stringnumber = 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.

Post a Comment for "Jquery Filter Numbers Of A String"