Reputation: 1007
I just found this code snippet that has to do with filtering hash tag but I don't understand what is it trying to do, and I'm not sure what to google either.
Thanks for the heads up...
var index = 0;
var hash = window.location.hash; //store the entered hash value eg, #02
if (hash) {
index = /\d+/.exec(hash)[0];
index = (parseInt(index) || 1) - 1;
}
Upvotes: 1
Views: 57
Reputation: 474
var hash = window.location.hash; //store the entered hash value eg, #02
Just gets the # part of the URL
if (hash) {
Checks if the hash is not empty
index = /\d+/.exec(hash)[0];
Tries to match the hash against a sequence of digits (that's what \d+ means) and assigns the first such sequence to index
index = (parseInt(index) || 1) - 1;
Just converts index to a number and decreases it by 1
If the hash contains no digits, this code throws an exception, so it's not very robust
Upvotes: 1
Reputation: 11363
In a regular expression \d
will match a single number. The +
in the regex will match repeats of the expression before it. So \d+
will match a full (all repetive) number.
So
"55".match(/\d+/) //=>["55"]
"55".match(/\d/) //=>["5"]
"A string with 55".match(/\d+/) //=>["55"]
Upvotes: 1
Reputation: 19423
if (hash) {
: If hash
is not a garbage value like undefined
, null
or empty string.index = /\d+/.exec(hash)[0]
: Look for the first number inside the hash, for example inside #432
that would be 432
(Note that the returned value is a string).index = (parseInt(index) || 1) - 1
: Try to convert index
to a number, if that worked out and the resulting number is not 0
then subtract 1
from the returned value, otherwise return 1
and then subtract 1
from it thus giving us 0
, the main idea here is that it seems we are trying to get an index to an array so the index can't be less than 0
.Upvotes: 2
Reputation: 56529
/\d+/
means one or more digits.
+
means one or more of the preceding element.
Also exec
If the match succeeds, the exec method returns an array and updates properties of the regular expression object. The returned array has the matched text as the first item, and then one item for each capturing parenthesis that matched containing the text that was captured.
If the match fails, the exec method returns null.
Upvotes: 1