Do Good
Do Good

Reputation: 1315

how retrieve the last portion of the url using regex or jquery

I have a url

/stars/planets/usa/en/universe/planet_stars.html

I need to get the planets_stars.html. How do I get that last portion alone?

Upvotes: 0

Views: 128

Answers (3)

Kaf
Kaf

Reputation: 33839

Using pure javascript:

var url = "/stars/planets/usa/en/universe/planet_stars.html";
var page = url.substring(url.lastIndexOf("/")+1);

Edit: second parameter of substring method optional and not required in this case. So, I removed it.

Upvotes: 1

jmar777
jmar777

Reputation: 39679

Neither jQuery nor regex necessary here:

url.split('/').pop();

Upvotes: 1

kemiller2002
kemiller2002

Reputation: 115538

or just JavaScript.

var parts = url.split('/');

var lastpart = parts[parts.length -1];

You can use pop() as jmar said too, just remember that removes it from the array when you do it, so you can't use the pop method twice on the same array and get the same value.

Upvotes: 0

Related Questions