扩展JS实现URL正则搜索,修改GTM辅助代码处理特定URL
Let's start by breaking down your existing code to make sure we're aligned:
function() {
var url = {{Page URL}};
if (url == "https://mywebsite.com/") {
url = "home";
} else {
url = url.split("/");
url = url[3].split("?");
url = url[0];
}
return url;
}
This code checks if the page is your homepage, returns "home" if so, otherwise splits the URL to grab the 4th segment (since arrays are zero-indexed) and strips any query parameters.
Now, to add differentiated handling for URLs that contain a specific string (I'll use special-content as an example—you can swap this with your actual target string), here's the updated code with comments explaining the changes:
function() { var url = {{Page URL}}; // Define your target specific string here var targetString = "special-content"; // Handle homepage case first if (url === "https://mywebsite.com/") { return "home"; } // Check if URL contains the specific string else if (url.includes(targetString)) { // Custom logic for URLs with the target string // Example 1: Return a fixed label for all matching URLs return "special-section"; // Example 2: Extract the segment right after the target string (uncomment to use) // url = url.split(targetString)[1].split("/")[1].split("?")[0]; // return url; } // Default handling for other non-homepage URLs else { url = url.split("/"); url = url[3].split("?"); return url[0]; } }
Key Tips for Customization:
- Replace
"special-content"with your actual target string—make sure it's unique enough to avoid accidental matches. - In the
else ifblock, adjust the logic to fit your needs: you can return a fixed label (like the first example) or extract a specific part of the URL relative to the target string (like the second example). - Using
===instead of==is a strict equality check that helps avoid unexpected type-related bugs in JavaScript. - If you need to match the string in a specific position (e.g., only when it's a full URL segment), you can modify the check to validate against the split URL segments instead of using
includes().
内容的提问来源于stack exchange,提问作者Schanzentroll

