Skip to content Skip to sidebar Skip to footer

Find And Get Only Number In String

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 re

Solution 1:

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).


Solution 2:

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);

Solution 3:

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).


Solution 4:

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.


Post a Comment for "Find And Get Only Number In String"