我有一个类似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。
当前回答
阅读Window。location和location接口:
const urlPieces = [location.]协议,'//',位置。主机,location.pathname] let url = urlPieces.join(") console.log ({urlPieces、url})
其他回答
只需将这两行添加到$(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”)
它会激活它们两个。
使用window.location的属性
var loc = window.location;
var withoutQuery = loc.hostname + loc.pathname;
var includingProtocol = loc.protocol + "//" + loc.hostname + loc.pathname;
您可以在https://developer.mozilla.org/en/DOM/window.location上查看更多属性
如果您正在使用导航栏,并希望在单击侧栏导航后获得纯url,那么以下代码可能会有帮助:
$(document).ready(function () {
$("div.sidebar nav a").removeClass("active");
var urlPath = window.location.pathname.split("?")[0];
var nav = $('div.sidebar nav a').filter(function () {
return $(this).attr('href').toLowerCase().indexOf(urlPath.toLocaleLowerCase()) > -1;
});
$(nav).each(function () {
if ($(this).attr("href").toLowerCase() == urlPath.toLocaleLowerCase())
$(this).addClass('active');
});
});
这里有两种方法:
<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 href = 'http://localhost/dms/mduserSecurity/UIL/index.php?menu=true&submenu=true&pcode=1235';/ / document.location.href const url =新的url (href); const noSearchUrl = href.replace(url。”); console.log (noSearchUrl);