Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove get variables and filename from URL using javascript/jquery?

I was looking into this issue but I couldn't find any solid answers for this specific purpose. Let's say I have a URL of...

http://mysite.com/stuff/index.php?search=my+search

How can I grab this URL and remove index.php?search=my+search from it so it would just be http://mysite.com/stuff/ ? Basically I just want to grab the parent URL without a filename or get variables... No matter what the URL (so I don't have to customize the function for every page I want to use it on)

So for an additional example, if it were just...

http://mysite.com/silly.php?hello=ahoy

I would just want to return the root of http://mysite.com

Can anyone give me a hand in figuring this out? I'm completely lost.

like image 253
Ian Avatar asked Feb 04 '12 22:02

Ian


1 Answers

Try using lastIndexOf("/"):

var url = "http://mysite.com/stuff/index.php?search=my+search";
url = url.substring(0, url.lastIndexOf("/") + 1);
alert(url); // it will be "http://mysite.com/stuff/"

OR

var url = "http://mysite.com/silly.php?hello=ahoy";
url = url.substring(0, url.lastIndexOf("/") + 1);
alert(url); // it will be "http://mysite.com/"
like image 108
Aliostad Avatar answered Oct 27 '22 00:10

Aliostad