繁体   English   中英

如何在 JavaScript 中使用多个分隔符拆分网站 URL?

[英]How do I split a website URL with multiple separators in JavaScript?

我正在尝试在 Google 跟踪代码管理器中创建一个自定义 JavaScript 变量,以从具有多个分隔符的页面 url 中拆分信息。 例如,在https://website.com/item/2006-yellow-submarine中,我想捕获2006 我一直在使用下面的代码一次基于一个分隔符(- 或 /)来分隔 URL。 但是,如果我使用下面的代码来拉 2006,它将拉 2006 以及之后的所有内容(所以拉的数据将是2006-yellow-submarine不仅仅是 2006 )。

function() {
  var pageUrl = window.location.href;
  return pageUrl.split("/")[4];
}

有没有办法只提取 2006,或者基本上使用 - 和 / 分隔符的组合从 URL 中提取单个路径点,而不必每次都在代码中指定 URL?

由于它是一个用于自动捕获每个页面上的年份的变量,因此我无法为网站的每个单独页面创建一个变量。 因此,该解决方案不能涉及指定 URL。

您可以按 RegExp 拆分,按/-拆分,即/[/-]/

 const u = new URL("https://website.com/item/2006-yellow-submarine"); const pathname = u.pathname; console.log(pathname); // skip the first item... it will always be empty const [, ...pathParts] = pathname.split(/[/-]/); console.log(pathParts);

为此,您可以这样做:

 function splitWebURL(url, loc1, loc2) { return url.split("/")[loc1].split("-")[loc2]; } var test = splitWebURL("https://website.com/item/2006-yellow-submarine", 4, 0); console.log(test);

它工作得很好,您只需更改 2 个索引号并更改 url 即可轻松更改它。

从字符串中创建一个新的 URL 对象,提取路径名的最后一部分,然后用一个小的正则表达式匹配年份。

 // Create a new URL object from the string const url = new URL('https://website.com/item/2006-yellow-submarine'); // `split` the pathname on "/", and `pop` off // the last element of that array const end = url.pathname.split('/').pop(); // Then match the year console.log(end.match(/[0-9]{4}/)[0]);

你可以做这样的事情

let year = window.location.href.match(/item\/([0-9]*)-/)[1];

假设您有一个类似于item/year-something的网址,

您将不得不处理 url 不匹配的情况,所以可能是这样的:

let match = window.location.href.match(/item\/([0-9]*)-/);
if(match && match.hasOwnProperty(1)) {
   let year = match[1]
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM