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.

6 comments:

  1. Im no expert, but I believe you just made an excellent You certainly understand what youre speaking about, and I can truly get behind that.
    Regards,

    Angular training in chennai|Angularjs training in chennai

    ReplyDelete
  2. Paris airport transfer - Parisairportransfer is very common in Paris that provides facilities to both the businessmen and the tourists. We provide airport transfers from London to any airport in London and also cruise transfer services at very affordable price to our valuable clients.

    Paris taxi
    Paris airport shuttle
    paris hotel transfer
    paris airport transfer
    paris shuttle
    paris car service
    paris airport service
    disneyland paris transfer
    paris airport transportation
    beauvais airport transfer
    taxi beauvais airport
    taxi cdg airport
    taxi orly airport

    ReplyDelete
  3. Useful Information
    one and only affiliate agency in south INDIA, earn money online from affiliate network in india

    ReplyDelete
  4. This is really great news. Thank you for sharing it with us!
    oracle training in chennai

    ReplyDelete