Reputation: 5
I cannot understand what this little snippet: var num = str.replace(/[^0-9]/g, '');
does.
Context:
function retnum(str) {
var num = str.replace(/[^0-9]/g, '');
var liczba = parseInt(num);
return liczba;
}
Upvotes: 0
Views: 76
Reputation: 989
This JavaScript snippet will rip out anything that is not (the ^
part of the regular expression means "not") a number in str
and then return an integer cast from the result as liczba
. See my comments:
// This function will return a number from a string that may contain other characters.
// Example: "1.23" -> 123
// Example: "a123" -> 123
// Example: "hg47g*y#" -> 47
function retnum(str) {
// First let's replace everything in str that is not a number with "" (nothing)
var num = str.replace(/[^0-9]/g, '');
// Let's use JavaScript's built in parseInt() to parse an Integer from the remaining string (called "num")
var liczba = parseInt(num);
// Let's now return that Integer:
return liczba;
}
By the way, "liczba" means number in Polish :-)
Upvotes: 2
Reputation: 161
It literally just replaces anything which is not a number with a blank ('').
Upvotes: 0
Reputation: 101
This function takes a string, strips all non-number characters from it, turns the string into an integer, and returns the integer. The line you're asking about specifically is the part that strips out all non-number characters from the initial string, using the string.replace method.
Upvotes: 2
Reputation: 32511
It's not obfuscated, it's using a regular expression.
The expression matches all things which are not numbers then removes them. 0-9
means "any digit" and the ^
means "not". The g
flag means to check the entire string instead of just the first match. Finally, the result is converted to a number.
Example:
var input = 'abc123def456';
var str = input.replace(/[^0-9]/g, '');
var num = parseInt(str);
document.querySelector('pre').innerText = num;
<pre></pre>
Upvotes: 0