1

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 Answers 4

1

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

var last = 'http://localhost:3000/developers/568d3c3c82eea6e6fb47c236'.split('/').pop();
//=> 568d3c3c82eea6e6fb47c236
Sign up to request clarification or add additional context in comments.

1 Comment

Doing a split is unnecessary.
1

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

Comments

1

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

var developerID = url.substr(url.lastIndexOf("/") + 1);

Comments

0

You can use following code snippet

var loc = location.href; 
var lastPart = loc.substr(loc.lastIndexOf('/') + 1);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.