JQuery: how to extract anchor from href

I am new to jQuery.

I would like to get the anchor value from href using jQuery.

If I had the following example, how could I get the value "5" from href using jQuery?

<a href="user/showUsers#5">User 5</a> 

Thank you in advance

-James

+6
source share
8 answers

Use the following:

 var id = $('a').attr('href').split('#'); id = id[id.length - 1]; 
+2
source

They are called "Hash." Say your link has an identifier, you can do it like this:

 document.getElementById("link").hash; 

This will give you a "#" anyway, but you can easily replace it:

 document.getElementById("link").hash.replace("#",""); 

Good luck

+1
source

If you want to get numbers indicating that the URL always follows the same structure, try this,

 $(document).ready(function() { var number = $("a").attr("href").match(/#([0-9]+)/)[1]; alert(number); }); 
+1
source

First you get href , and then you get the part after the first # :

 var href = $("selector_for_the_link").attr('href'), index = href.indexOf('#'), anchor = href.substring(index + 1); 
0
source

This will bind all anchor tags to some associated href value

 $('a[href*="#"]').each(function(){ if(this.href.split('#').length>1 && this.href.split('#')[1] != ""){ console.log(this.href.split('#')[1]); } }); 
0
source

If you are going to use this in several places, or if you just want to get cleaner code, I suggest you take a look at this URL parser .

Once you have installed it, you simply use it as follows:

 var anchor = $.url('http://yoursite.com/user/showUsers#5').attr('anchor'); 
0
source
  var id = $(this).attr("href").split("#"); id = id[id.length - 1]; 
-1
source

Suppose there will no longer be a "#".

 <script type="text/javascript" language="javascript"> function GetAnchorValue(CurrCtrl) { var hrefText = $(CurrCtrl).attr("href"); var RequiredValue; if(hrefText.indexOf("#") != -1) { RequiredValue = hrefText.split("#")[1]; } } </script> 
Tag

html will be

 <a href="user/showUsers#5" onclick="return GetAnchorValue(this);">Test Anchor</a> 
-1
source

All Articles