0

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?

6
  • find last index of ('/') Commented May 15, 2012 at 14:30
  • or .. use this: /([^\/]+)$/ Commented May 15, 2012 at 14:33
  • str.substr(str.lastindexof('/')); something like this Commented May 15, 2012 at 14:42
  • Will you ever have to deal with URLs with query parts or fragment IDs? They make things quite a lot more complex… Commented May 15, 2012 at 14:44
  • 1
    @DoGood every time you are asking something, you should be polite and accept answers(vote up, i think and put green tick to this answer (under vote arrows)) Commented May 15, 2012 at 14:45

3 Answers 3

1

Neither jQuery nor regex necessary here:

url.split('/').pop();
Sign up to request clarification or add additional context in comments.

2 Comments

using of LastIndex + SubStr will be more elegant in this task.
That seems rather subjective. I think brevity of code is nice, and this approach reads nicely to me.
1

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.