我无法在标题中解释自己。我想要的是在斜杠之间获取字符串。像那样: www.example.com/foo/bar/id/1 我想得到“foo”。因为我做了这些代码。
select: function(event, ui) {
if(window.location.href = "news/" + ui.item.slug){
window.location.href =null;
}
else
window.location.href ="news/" + ui.item.slug;
}
我有一个自动完成搜索字段。当我点击一个结果时,它会将我重定向到 www.example.com/news/34523 在此页面中,如果我再次使用搜索字段,它会将我重定向到 www.example.com/news/news/12412 之后我得到 404。但是如果我不在新闻选项卡中,例如 < strong>www.example.com/foo 当我使用搜索字段时,它工作得很好。我只需要一个 if 语句,如果我在新闻页面中就像另一个页面一样。
最佳答案
您可以简单地使用 location.pathname
属性来获取第一个和第二个斜杠之间的部分,并基于此运行代码。
console.log(window.location.pathname);
console.log(window.location.pathname.split("/")[1] === "foo");
为了证明这是有效的,这是另一个片段,就好像 url
是 window.location
:
let url = document.createElement('a');
url.href = "http://www.example.com/foo/bar/id/1";
console.log(url.pathname);
console.log(url.pathname.split("/")[1] === "foo");
关于javascript - 如何在jquery中获取当前的url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50217130/