views:

90

answers:

4

Hello dear friends !

Please help me solve this strange situation:

Here is code:

The link is so - www.blablabla.ru#3

The regex is so:

var id = window.location.href.replace(/\D/, '' );
alert(id);

The regular expression is correct - it must show only numbers ... but it's not showing numbers :-(

Can you please advice me and provide some informations on how to get only numbers in the string ?

Thanks

+1  A: 

Use the flag /\D/g, globally replace all the instances

var id = window.location.href.replace(/\D/g, '' );
alert(id);

And /\D+/ gets better performance than /\D/g, according to Justin Johnson, which I think because of \D+ can match and replace it in one shot.

S.Mark
`/\D+/g` is about 30% faster than `/\D/g` See my response to Ivan's answer
Justin Johnson
Thanks for the benchmark, I think its because of \D+ can match in a one shot
S.Mark
You rule , thanks !!
Vovan
Exactly. Instead iterating `O(nm)` times, where `n` is the number of digit groups and `m` is the number of digits in a group, it's just `O(n)`.
Justin Johnson
+5  A: 

You're replacing only the first non-digit character with empty string. Try using:

var id = window.location.href.replace(/\D/g, '' ); alert(id);

(Notice the "global" flag at the end of regex).

Ivan Vrtarić
You rule man, thanks !
Vovan
My tests show that it is about 30% more efficient to use `/\D+/g` instead of just `/\D/g`. var r1 = /\D/g, r2 = /\D+/g, s = "", MAX = 1020, i = MAX;do { s += (i%2) ? "aaaaaaaaaaa" : "11111111111"; } while (--i);console.time("\\D");for ( var i=0; i<MAX; ++i ) { s.replace(r1, "");}console.timeEnd("\\D");console.time("\\D+");for ( var i=0; i<MAX; ++i ) { s.replace(r2, "");}console.timeEnd("\\D+");
Justin Johnson
+2  A: 

Edit: See Kobi's answer. If you really are using the hash part of things, just use location.hash! (To self: Doh!)

But I'll leave the below in case you're doing something more complex than your example suggests.

Original answer:

As the others have said, you've left out the global flag in your replacement. But I'm worried about the expression, it's really fragile. Consider: www.37signals.com#42: Your resulting numeric string will be 3742, which probably isn't what you want. Other examples: www.blablabla.ru/user/4#3 (43), www2.blablabla.ru#3 (23), ...

How 'bout:

id = window.location.href.match(/\#(\d+)/)[1];

...which gets you the contiguous set of digits immediately following the hash mark (or undefined if there aren't any).

T.J. Crowder
There's location.hash. :)
Georg
@Georg: LOL!! Of course there is, and it's the better answer (looks like Kobi's posted it now). I'll leave this (edited) in case he's not actually using the hash but that was just his example.
T.J. Crowder
+4  A: 

Consider using location.hash - this holds just the hashtag on the end of the url: "#42".
You can write:

var id = location.hash.substring(1);
Kobi
You rule man, thanks !
Vovan