javascript - Getting the last string of a link - Stack Overflow

I have been searching for a while with no success, I found ways to get the current URL but can't f

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

/

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

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

Share Improve this question asked Nov 10, 2014 at 3:36 DlacremDlacrem 713 silver badges10 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

$('.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./ajax/libs/jquery/1.11.1/jquery.min.js"></script>

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

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744761532a4592204.html

相关推荐

  • javascript - Getting the last string of a link - Stack Overflow

    I have been searching for a while with no success, I found ways to get the current URL but can't f

    9小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信