Get Last Segment of URL in JavaScript

Posted on April 4, 2013

JavaScript handles strings and arrays very well. Sometime its needed to get the last segment or file name of the current page URL and process it for another JavaScript/Ajax request.

Here, I would like to share a fairly easy way.

Let current page URL is http://www.sidd3.com/segment1/segment2/segment3/segment4

Code Example:


<script type="text/javascript">

var segment_str = window.location.pathname; // return segment1/segment2/segment3/segment4
var segment_array = segment_str.split( '/' );
var last_segment = segment_array[segment_array.length - 1];
alert(last_segment); // alerts segment4

</script>

For the same purpose, JavaScript array function pop() can be used.

Code Example:


<script type="text/javascript">

var segment_str = window.location.pathname; // return segment1/segment2/segment3/segment4
var segment_array = segment_str.split( '/' );
var last_segment = segment_array.pop();
alert(last_segment); // alerts segment4

</script>