我有一个类似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的属性
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上查看更多属性
其他回答
这个怎么样:location。href。切片(0,- (location。Search + location.hash).length))
试试这个:
让path = window.location. hrf .split('?')[0] console.log ({path})
location.toString().replace(location.search, "")
你可以创建一个URL实例,然后清除查询字符串:
const url = new URL(document.location.href);
url.search = '';
console.log(url.href);
如果您正在使用导航栏,并希望在单击侧栏导航后获得纯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');
});
});