开发者

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 regular expression is correct - it must show onl开发者_运维百科y 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


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


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜