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

Asked

Viewed 44,529 times

18

I wonder if there are functions that return only the numeric values of a string, if there is not, what is the simplest and efficient way to implement?

Example:

apenasNumeros("5tr1ng");

Upshot:

51

7 answers

27

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

The simplest way:

  1. Use regex to delete all non-number characters.
  2. Make parse for whole

Note

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

Parse of numbers above 2 53 results in a loss of accuracy - 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.

  • +1 better than my answer, I don’t know how I didn’t think of it!

  • test like this: apenasNumeros("(48) 3442-7131_1234_4321123") you’ll have some 0's that do not exist :p

  • @mgibsonbr heh thanks :) also started by a much more complicated solution!

  • I noticed that after 20 characters a zero starts to appear at the end, because? -I found out I think it’s because of the firebug kkk console

  • 3

    A detail that perhaps the author of the question does not know: if the numbers are at the beginning, only the parseInt suffice (parseInt("51foo") === 51).

  • 1

    @Pauloroberto good question. I think this is because the javascript integers represent themselves with 64 bits. This allows representing a maximum integer of 9007199254740992

  • yeah, you could even solve by taking the result as string with the numbers and check if the length is greater than 20, if not convert to whole, if it is, separate into two variables or anything of the type, but your solution is correct, the proleme is javascript =p

  • I added a note regarding' loss of accuracy. Also, thanks for the @bfavaretto remark ;)

  • Very good explanation of accuracy, @dcastro!

  • Since you are talking about working with numbers larger than 52bits, there are libs to support, for example this: http://jsfromhell.com/classes/bignumber

Show 5 more comments

7


The leanest way I can imagine to do that:

"5tr1ng0".split("").filter(n => (Number(n) || n == 0)).join("");

or:

'5tr1ng0'.replace(/([^\d])+/gim, '');

or:

'5tr1ng0'.replace(/\D/gim, '');
  • Sincerely I loved this your solution, it totally reflects Javascript in its full way of being simple and efficient and one Liner whenever possible, outside that there is no limitation of decimal accuracy :D

  • But... I just found a catch, what about Zero? It doesn’t work because he’s not considered a Number, but a Falsy

  • 1

    "00000000aaaaaaaaa1".split(``).filter(n => Number(n) || n == false).join(``) this one works

  • Great, I added it to stay the way you need it.

6

I don’t 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 looking for numbers (\d), non-stop at first found (flag g). As it returns the results as an array, you can give a join('') to put together everything I renew and parseInt if you wish to perform some mathematical operation with it.

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

$num     = $string.match(/\d/g);
  • I believe this method has more operations resulting in a lower performance. But the idea is good!

4

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

  1. A regex \D+ takes everything that is not number;
  2. Making split around this expression, we divide the string into "pieces" using this regex as the delimiter: ["5", "1", ""];
  3. Making the join, we put her back together in a string: "51";
  4. Finally the parseInt interprets the string as a number (at base 10; it is always important to specify the base, to avoid "zero left errors"): 51.

Example in jsFiddle. As for "more efficient", it will depend on your particular case (is a gigantic string? is a lot of small strings? etc), but the generic answer is "it doesn’t make much difference in practice"... (i.e. in most cases, the difference in performance between any "reasonable" solution will be negligible)

2

Simply remove all characters that are not numbers using the following regex:

string.replace(/\D/g, '') // substitui o que nao for numero por nada

Example:

var str = '(11) 2222-3333_4444_5555$6.777.-@8-!9';
var nums = str.replace(/\D/g, '');
console.log(nums);

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 function filter, as follows

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

-1

easiest way I found:

    function somenteNumeros(num) {
      var tecla = event.keyCode;
      return (tecla > 47 && tecla < 58)
    }
<input type="text" onkeypress="return somenteNumeros(this)"/>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.