How to get only the numbers of a string in Javascript?

16

I would like to know if there are functions that return only the numeric values of a string, if any, which is the simplest and most efficient way to implement?

Example:

apenasNumeros("5tr1ng");

Result:

  

51

    
asked by anonymous 01.02.2014 / 13:17

4 answers

21
function apenasNumeros(string) 
{
    var numsStr = string.replace(/[^0-9]/g,'');
    return parseInt(numsStr);
}

The simplest way:

  • Use a regex to delete all non-numeric characters.
  • Parsing entire
  • Note

    Internally, javascript represents integer numbers as a 64-bit floating point (52 bits reserved for the mantissa). This means that the above function can parse integers up to +/- 9007199254740992 (2 ^ 53).

    Parsing numbers above 2 ^ 53 results in a loss of precision - that is, 0's will be added. parseInt("90071992547409925") results in 90071992547409920

    The alternative would simply be to return the result of replace (a string), without parsing for integer.

        
    01.02.2014 / 13:33
    4

    I do not know if my solution is better than the others, but it seems simpler, at least:

    $string = "l337 5tr1ng";
    $num    = parseInt($string.match(/\d/g).join(''));
    

    The match looks for numbers ( \d ), non-stop on the first found (flag g ). Since it returns the results as an array, you can give join('') to join all renew and parseInt if you want to perform any math operation with it.

    If you just want to get all the numbers in an array, just:

    $num     = $string.match(/\d/g);
    
        
    01.02.2014 / 15:26
    3

    One way is parseInt(str.split(/\D+/).join(""), 10) .

  • regex \D+ takes everything that is not number;
  • By doing split around this expression, we divide the string into "pieces" using this regex as a delimiter: ["5", "1", ""] ;
  • By doing join , we put it back in a string: "51" ;
  • Finally, parseInt interprets the string in a number (in base 10; it is always important to specify the base, to avoid "zero left" errors): 51 .
  • Example in jsFiddle . As for "most efficient", it will depend on your particular case (it's a gigantic string - is it a bunch of small strings?), But the generic answer is "it does not make much difference in practice" ... of cases, the performance difference between any "reasonable" solution will be negligible)

        
    01.02.2014 / 13:32
    2

    You can use isNaN to check if the variable is not a number,

    isNaN(num) // retorna true se num não contém num número válido
    

    combined with the filter function, as follows

    "5tr1ng".split('').filter(function(ele){
        return !isNaN(ele);
    }).join(''); // retorna "51"
    
        
    20.11.2014 / 12:20