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

∥☆過路亽.° 提交于 2020-06-24 23:21:59

问题


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.


回答1:


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/"



回答2:


If your url is in str:

newstr = str.replace(/\/[^\/]+$/,"");

newstr now contains the path up to but excluding the last / in the string. To keep the final /, use:

newstr = str.replace(/\/[^\/]+$/,"/");



回答3:


split on "/", discard the last piece, join them back up, add trailing slash.

var path = location.href.split('/');
path.pop();
path = path.join("/") + "/";



回答4:


You're looking for location.host or location.hostname. But would you like to extract them from a complete string rather than from current URL?

I read the question once more and it seems you want get the string which consists of:

location.protocol + "//" + location.host + location.pathname

right?



来源:https://stackoverflow.com/questions/9145118/how-do-i-remove-get-variables-and-filename-from-url-using-javascript-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!