1

I have a url in this form http://www.example.com/data/45. How do I get the last element (45 in this example) using jQuery or JavaScript?

Thanks.

3 Answers 3

7

A very quick plain JavaScript method, assuming it's the URL of the current page (in window.location.href)

var urlNum = window.location.href.split('/').pop();

.split('/') obviously chops the URL up into an array, based on divisions by /. Since you only need the last part, it is probably the easiest method.

.pop() removes the last element from the array returned by .split() and returns it.

Sign up to request clarification or add additional context in comments.

Comments

1
var num = 'http://www.example.com/data/45'.split('/').pop(); //num now == '45'

Comments

0

My rendition :)

var url         = 'http://www.example.com/data/45';
var lastSegment = url.substr(url.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.