Getting the last string of a link

4.3k Views Asked by At

I have been searching for a while with no success, I found ways to get the current URL but can't figure out how to get the last string for a specific link.

The Url would be something like

http://www.mywebsite.com/slug/

What I would need to get is the "slug" part out of the link's URL

My current function:

$('.filters a').click(function(e){
e.preventDefault();
var slug = '';
alert ( slug );
});

Any help will be appreciated :)

2

There are 2 best solutions below

0
On BEST ANSWER

$('.filters a').click(function (e) {
    e.preventDefault();
    var slug = $(this).attr('href').split('/');
    slug = slug[slug.length - 2];
    alert(slug);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div class="filters">
   <a href="http://www.mywebsite.com/slug/">Slug Link</a>
</div>

0
On

You can try a regex like

$('.filters a').click(function (e) {
    e.preventDefault();
    var slug = $(this).attr('href').match(/[^/]*(?=(\/)?$)/)[0];
    alert(slug);
});
  • [^/]* - 0 or more characters other than /
  • (?=(\/)?$) which is followed by 0 or 1 instance / and line end