Thursday, June 4, 2015

How To Get URL And Extract URL Segments Using jQuery?

It is easy to get URL and extract the URL segments dynamically using jQuery.In the below example, I have shown how to get the URL dynamically or setting the URL statically and extract parts or segments of URL.
//Getting the URL dynamically
var url = $(location).attr('href');

//Setting the URL statically
var url = 'http://www.example.com/segment1/example.html';

// Getting the file name i.e last segment of URL (i.e. example.html)
var fn = url.split('/').reverse()[0];

// Getting the extension (i.e. html)
var ext = url.split('/').reverse()[0].split('.').reverse()[0];

// Getting the second last segment of URL (i.e. segment1)
var lm = url.split('/').reverse()[1];
In the above example split the string URL when find "/" (separator) and use reverse save it in an array. Then using the proper index, you can get any part of URL you need (in the above example, we retrieved file name (last segment of URL), extension of file and second last segment of URL).

There are many other ways to get URL and extract URL segments using jQuery. Do share if you have any other good ideas.

4 comments: