Is there any method to get the URL without query s

2019-01-10 02:36发布

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.

11条回答
Explosion°爆炸
2楼-- · 2019-01-10 02:51

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.

查看更多
神经病院院长
3楼-- · 2019-01-10 02:52

Read about Window.location and the Location interface:

var url = [location.protocol, '//', location.host, location.pathname].join('');
查看更多
疯言疯语
4楼-- · 2019-01-10 02:54

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]);
查看更多
兄弟一词,经得起流年.
5楼-- · 2019-01-10 02:56

Try:

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

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

查看更多
欢心
6楼-- · 2019-01-10 02:56

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>
查看更多
相关推荐>>
7楼-- · 2019-01-10 03:03

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

查看更多
登录 后发表回答