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
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?
apenasNumeros("5tr1ng");
51
function apenasNumeros(string)
{
var numsStr = string.replace(/[^0-9]/g,'');
return parseInt(numsStr);
}
The simplest way:
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.
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);
One way is parseInt(str.split(/\D+/).join(""), 10)
.
\D+
takes everything that is not number; split
around this expression, we divide the string into "pieces" using this regex as a delimiter: ["5", "1", ""]
; join
, we put it back in a string: "51"
; 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)
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"