Regular Expressions in JavaScript for URL Capture

2020-04-21 07:39发布

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:

http://localhost:3000/developers/568d3c3c82eea6e6fb47c236

And all I need to do is capture the developer ID (which is 568d3c3c82eea6e6fb47c236). This route will always be the same (with just the ID's changing).

Any help would be much appreciated

4条回答
啃猪蹄的小仙女
2楼-- · 2020-04-21 08:11

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

var last = 'http://localhost:3000/developers/568d3c3c82eea6e6fb47c236'.split('/').pop();
//=> 568d3c3c82eea6e6fb47c236
查看更多
虎瘦雄心在
3楼-- · 2020-04-21 08:11

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

var developerID = url.substr(url.lastIndexOf("/") + 1);
查看更多
唯我独甜
4楼-- · 2020-04-21 08:13

You can use following code snippet

var loc = location.href; 
var lastPart = loc.substr(loc.lastIndexOf('/') + 1);
查看更多
够拽才男人
5楼-- · 2020-04-21 08:22

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()).

查看更多
登录 后发表回答