04 February 2019

How To Get URL And Extract URL Segments Using jQuery?

It's easy to get URL and Extract URL Segments using jQuery. in some cases you will find something like this. So, here's how to get it:

 //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.
Or
i.e ?param1&param2

you can change url.split('?') for get parameters.

url[1] then you get param1=1&param2=2

No comments: