Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Filter Numbers Of A String [duplicate]

How do you filter only the numbers of a string?

Example Pseudo Code:
number = $("thumb32").filternumbers()
number = 32
like image 653
Tomkay Avatar asked Sep 10 '25 02:09

Tomkay


2 Answers

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];
like image 155
Jonathon Bolster Avatar answered Sep 12 '25 16:09

Jonathon Bolster


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.

like image 28
Pointy Avatar answered Sep 12 '25 16:09

Pointy