Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 510
Vladimir Lukyanov Avatar asked Feb 24 '10 08:02

Vladimir Lukyanov


2 Answers

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

like image 184
Ivan Vrtarić Avatar answered Oct 26 '22 15:10

Ivan Vrtarić


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);
like image 30
Kobi Avatar answered Oct 26 '22 14:10

Kobi