How to get the last part of url AngularJS

前端 未结 2 694
小蘑菇
小蘑菇 2021-01-15 02:57

How to build the function in AngularJS to chceck the last part of the url?

My examples:

#/menu1/123/edit

#/menu2/444/create/new<

相关标签:
2条回答
  • 2021-01-15 03:07

    This should give you the desired result:

    window.alert(window.location.href.substr(window.location.href.lastIndexOf('/') + 1));
    

    You could get the current URL by using: window.location.href Then you only need to get the part after the last '/'

    0 讨论(0)
  • 2021-01-15 03:25

    More efficient way:

    location.pathname.split('/').slice(-1)[0]
    

    In case of http://example.com/firstdir/seconddir/thirddir?queryparams#hash; it will give you thirddir

    • pathname will keep only the part of url after domain name and before query params
    • split will explode the url into array separated by /
    • slice will give you array containing only the last item
    • [0] will you last item as a string (in contrast to item of an array)
    0 讨论(0)
提交回复
热议问题