0

my url is following:

http://localhost:8000/business/products/category/1

and i want to get the last 1 parameter from URL using jquery. Is there any method to do so?

Thanks in advance..

4 Answers 4

2

Using split() creates an array, pop() returns last element of array

alert(location.pathname.split('/').pop())/// alerts 1
Sign up to request clarification or add additional context in comments.

Comments

0

this will get last segment even with different number of segments:

$segs = $this->uri->segment_array();
echo end($segs);

1 Comment

end($segs); end() is PHP inbuilt.
0

You can either do this by getting it from php and embedding it into the javascript:

var category = <?php echo $this -> uri -> uri_to_assoc()['category'] ?>;

OR using only javascript

var url = window.location.href;
var idx = url.indexOf("category");
var category = url.substring(idx).split("/")[1];

Comments

0

You can achieve this by splitting the URL into segment first.

Try like this

var segments = url.split( '/' );
var action = segments[3];
var id = segments[4];

You get the URL using Jquery like this

$(location).attr('href');

2 Comments

what about the slashes in protocol? easier to use location.pathname as base
Yeah. If you want to get path or url use like this var pathname = window.location.pathname; // Returns path only var url = window.location.href; // Returns full URL

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.