Regular Expressions in JavaScript for URL Capture

前端 未结 4 1200
耶瑟儿~
耶瑟儿~ 2021-01-25 03:08

I am not too good with Regular Expressions in Javascript. Does anyone know an efficient way to capture the last portion of a URL???

I have the following URL:

<         


        
相关标签:
4条回答
  • 2021-01-25 03:45

    There are built in methods for this:

    window.location.pathname.split("/").pop()
    

    This will get everything after the domain name (window.location.pathname), then split it by forward slashes (split("/")), then return the last item of the array returned by split(), (pop()).

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

    You can use following code snippet

    var loc = location.href; 
    var lastPart = loc.substr(loc.lastIndexOf('/') + 1);
    
    0 讨论(0)
  • 2021-01-25 03:55

    You can use split by / and get the last element of srray:

    var last = 'http://localhost:3000/developers/568d3c3c82eea6e6fb47c236'.split('/').pop();
    //=> 568d3c3c82eea6e6fb47c236
    
    0 讨论(0)
  • 2021-01-25 03:58

    You don't need a regular expression; just use lastIndexOf method:

    var developerID = url.substr(url.lastIndexOf("/") + 1);
    
    0 讨论(0)
提交回复
热议问题