英文:
how to check whether window.location.pathname ends with /search?
问题
我正在尝试跟踪页面访问,当有人进入搜索结果页面时。目前我有一个名为isMatch的函数,如果它返回true,那么它会发送一个事件。
是否有一种方法可以检查window.location.pathname,基本上检查它是否以/search?
结束?以下是有人搜索时的示例URL:
https://website.com/en_US/search?q=testin&search-button=&lang=en_US
其中"testin"是用户在搜索栏中输入的内容。
目前,我有:
isMatch: () => {
const urlParams = new URLSearchParams(window.location.search);
const paramValue = urlParams.get("q");
return paramValue !== null && window.location.pathname === "/en_US/search";
}
但是我想要检查它是否以"search"结束,这样我就不必包含区域设置(en_US),因为我们希望在多个国家跟踪这个,而不必更改代码。像window.location.hash
这样的东西会起作用吗?我对它不是很熟悉。
英文:
I am trying to track a page visit when someone lands on a search results page. Right now I have an isMatch function, and if it returns true, then it sends an event.
Is there a way to check against window.location.pathname, to basically check whether or not it ends with /search?
? Here is an example URL when someone searches:
https://website.com/en_US/search?q=testin&search-button=&lang=en_US
Where "testin" is what the user inputted in the search bar.
Right now, I have:
isMatch: () => {
const urlParams = new URLSearchParams(window.location.search);
const paramValue = urlParams.get("q");
return paramValue !== null && window.location.pathname === "/en_US/search";
However I want to check against if it ends with search so I don't have to include the locale (en_US) since we want to track this on multiple countries without having the change the code. Would something like window.location.hash
work? I am not totally familiar with it.
答案1
得分: 2
- endWith()
return window.location.pathname.endsWith("/search");
请注意,endsWith() 不支持 IE 11(或更早版本)
- substring()
let path = window.location.pathname;
return path.substring(path.length - 7) === "/search";
英文:
You can use these two methods to handle it:
- endWith()
return window.location.pathname.endsWith("/search");
> Please Note that endsWith() is not supported in IE 11 (or earlier versions)
- substring()
let path= window.location.pathname;
return path.substring(path.length-7) === "/search";
答案2
得分: 1
JavaScript中,字符串具有endsWith
方法,它的工作方式如您所期望。
window.location.pathname.endsWith("/search");
英文:
In JavaScript, strings have the method endsWith
, which works as you'd expect.
window.location.pathname.endsWith("/search");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论