I'm trying to create a Custom JavaScript Variable in Google Tag Manager to split up information from a page url that has multiple separators. For example, in https://website.com/item/2006-yellow-submarine, I would want to capture the 2006. I've been using the code below to separate a URL based on one separator at a time (- or /). But if I used the code below to pull 2006, it would pull 2006 and everything after (so the data pulled would be 2006-yellow-submarine and not just 2006).
function() {
var pageUrl = window.location.href;
return pageUrl.split("/")[4];
}
Is there a way to extract only the 2006, or to essentially use a combination of - and / separators to pull single path points from a URL, without having to specify the URL in the code each time?
Since it's a variable meant to be used to automatically capture the year on each page, I can't make a variable for every individual page of the website. Therefore the solution can't involve specifying the URL.
CodePudding user response:
You can split by RegExp, splitting by either /
or -
, i.e. /[/-]/
:
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);
CodePudding user response:
You could do something like that
let year = window.location.href.match(/item\/([0-9]*)-/)[1];
assuming you have an url that's like item/year-something
,
you will have to handle the cases where the url does not match though, so perhaps like that :
let match = window.location.href.match(/item\/([0-9]*)-/);
if(match && match.hasOwnProperty(1)) {
let year = match[1]
}
CodePudding user response:
Make a new URL object from the string, extract the last part of the pathname, and then match the year with a small regular expression.
// 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]);
CodePudding user response:
To do this you could do this:
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);
It works great and you can change it with ease by just changing the 2 index numbers and changing the url.