我有一个类似http://localhost/dms/mduserSecurity/UIL/index.php?menu=true&submenu=true&pcode=1235的URL。
我想获得不带查询字符串的URL: http://localhost/dms/mduserSecurity/UIL/index.php。
JavaScript中有没有这种方法?目前我正在使用document.location。href,但它返回完整的URL。
我有一个类似http://localhost/dms/mduserSecurity/UIL/index.php?menu=true&submenu=true&pcode=1235的URL。
我想获得不带查询字符串的URL: http://localhost/dms/mduserSecurity/UIL/index.php。
JavaScript中有没有这种方法?目前我正在使用document.location。href,但它返回完整的URL。
当前回答
这里有两种方法:
<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>
其他回答
你可以创建一个URL实例,然后清除查询字符串:
const url = new URL(document.location.href);
url.search = '';
console.log(url.href);
只需将这两行添加到$(document)。在JS中准备如下:
$(document).ready(function () {
$("div.sidebar nav a").removeClass("active");
$('nav a[href$="'+ window.location.pathname.split("?")[0] +'"]').addClass('active');
});
最好使用美元符号($)(以)结尾
$('nav a[href$
而不是(^)(以)开头
$('nav a[href^
因为,如果你使用(^)符号并且你在导航菜单中有嵌套的url,(例如“/account”和“/account/roles”)
它会激活它们两个。
下面是一个使用URL()接口的方法:
new URL(location.pathname, location.href).href
只需使用split(简单的方法)切割字符串:
var myString = "http://localhost/dms/mduserSecurity/UIL/index.php?menu=true&submenu=true&pcode=1235"
var mySplitResult = myString.split("?");
alert(mySplitResult[0]);
获取除了查询之外的URL的所有部分:
var url = (location.origin).concat(location.pathname).concat(location.hash);
注意,如果有哈希的话,这里也包括哈希(我知道示例URL中没有哈希,但为了完整起见,我包含了这个方面)。要消除散列,只需排除.concat(location.hash)。
使用concat将Javascript字符串连接在一起(而不是+)是更好的实践:在某些情况下,它可以避免类型混淆等问题。