如何检查`window.location.pathname`是否以`/search`结尾?

huangapple go评论69阅读模式
英文:

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

  1. endWith()
    return window.location.pathname.endsWith("/search");

请注意,endsWith() 不支持 IE 11(或更早版本)

  1. substring()
    let path = window.location.pathname;
    return path.substring(path.length - 7) === "/search";
英文:

You can use these two methods to handle it:

  1. endWith()
    return window.location.pathname.endsWith("/search");

> Please Note that endsWith() is not supported in IE 11 (or earlier versions)

  1. 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");

huangapple
  • 本文由 发表于 2023年2月6日 13:10:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75357525.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定