我有一个类似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。
当前回答
你可以像这样使用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);
其他回答
如果您正在使用导航栏,并希望在单击侧栏导航后获得纯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');
});
});
Try:
document.location.protocol + '//' +
document.location.host +
document.location.pathname;
(注意:.host而不是.hostname,这样端口也包括在内,如果需要的话)
试试这个:
让path = window.location. hrf .split('?')[0] console.log ({path})
location.toString().replace(location.search, "")
获取除了查询之外的URL的所有部分:
var url = (location.origin).concat(location.pathname).concat(location.hash);
注意,如果有哈希的话,这里也包括哈希(我知道示例URL中没有哈希,但为了完整起见,我包含了这个方面)。要消除散列,只需排除.concat(location.hash)。
使用concat将Javascript字符串连接在一起(而不是+)是更好的实践:在某些情况下,它可以避免类型混淆等问题。