我如何修改我的JS代码与我的新URL结构的工作

How do I modify my JS code to work with my new URL structure?

本文关键字:我的 URL 结构 工作 代码 JS 何修改 修改      更新时间:2023-09-26

我正在尝试从URL中提取搜索字符串。

当URL看起来像这样时,我可以这样做:

http://domain.com/search/keyword

,而不是当URL看起来像这样:

http://domain.com/#/search/keyword

下面是我的第一个例子的Javascript代码,除了我不能让它工作,现在的URL结构已经改变。

function () {
  // find and store the path of the current page
  var pagePath = location.pathname;
  // if the path starts with /search/, we know it's an internal SERP
  if (pagePath.indexOf("/search/") === 0) {
    // if the above checks out, let's figure out where the search term begins in the URL. Then, let's use that starting point to pull out the search term itself.
    var searchString = pagePath.substring(pagePath.lastIndexOf("/") + 1);
    // return what we found to GTM as the value of our variable
    return searchString;
  }
  // if it's not an internal SERP page, return "none"
  else {
    return "none";
  }
}
当URL结构看起来像这样时,上面的代码可以正常工作: http://domain.com/search/keyword

而不是像这样:

http://domain.com/#/search/keyword

问题是:我如何修改我的JS代码上面的工作与我的新URL结构?

我已经尝试改变我的JS代码的一部分:

  if (pagePath.indexOf("/search/") === 0) {

  if (pagePath.indexOf("/#/search/") === 0) {

但是我不能使它工作。请帮忙:)

散列符号#表示url片段,不属于pathname。您可以使用location.hash

访问url片段。