Is there any method to get the URL without query s

2019-01-10 02:17发布

问题:

I have a URL like http://localhost/dms/mduserSecurity/UIL/index.php?menu=true&submenu=true&pcode=1235.

I want to get the URL without the query string: http://localhost/dms/mduserSecurity/UIL/index.php.

Is there any method for this in JavaScript? Currently I am using document.location.href, but it returns the complete URL.

回答1:

Try this: window.location.href.split('?')[0]



回答2:

Read about Window.location and the Location interface:

var url = [location.protocol, '//', location.host, location.pathname].join('');


回答3:

location.toString().replace(location.search, "")


回答4:

var url = window.location.origin + window.location.pathname;


回答5:

If you also want to remove hash, try this one: window.location.href.split(/[?#]/)[0]



回答6:

Try:

document.location.protocol + '//' +
document.location.host +
document.location.pathname;

(NB: .host rather than .hostname so that the port gets included too, if necessary)



回答7:

just cut the string using split (the easy way):

var myString = "http://localhost/dms/mduserSecurity/UIL/index.php?menu=true&submenu=true&pcode=1235"
var mySplitResult = myString.split("?");
alert(mySplitResult[0]);


回答8:

To get every part of the URL except for the query:

var url = (location.origin).concat(location.pathname).concat(location.hash);

Note that this includes the hash as well, if there is one (I'm aware there's no hash in your example URL, but I included that aspect for completeness). To eliminate the hash, simply exclude .concat(location.hash).

It's better practice to use concat to join Javascript strings together (rather than +): in some situations it avoids problems such as type confusion.



回答9:

Here are two methods:

<script type="text/javascript">
    var s="http://localhost/dms/mduserSecurity/UIL/index.php?menu=true&submenu
                                =true&pcode=1235";

    var st=s.substring(0, s.indexOf("?"));

    alert(st);

    alert(s.replace(/\?.*/,''));
</script>


回答10:

How about this: location.href.slice(0, - ((location.search + location.hash).length))



回答11:

Use properties of window.location

var loc = window.location;
var withoutQuery = loc.hostname + loc.pathname;
var includingProtocol = loc.protocol + "//" + loc.hostname + loc.pathname;

You can see more properties at https://developer.mozilla.org/en/DOM/window.location