I am trying to write a function in JavaScript (or any clientside technology that is capable of it) to allow a URL to be tested against a list of URLs that are to be tracked (using Bing Conversion Tracking). I have the bases of what is required but I am unsure of how its meant to be applied.
var isCorrectPage = false;
//loop through list of URLS
isCorrectPage = true;
if (isCorrectPage) {
// enter the bespoke tracking code
}
I am unsure of exactly the way it checks the validity of the URL, should I then loop through a list of the selected URLs for tracking?
@ Ivan Nevostruev I want to filter some URLs that will be similar but have different page numbers, The URLs are like:
"/find-enquiry-thanks.aspx?did=62"
"/find-enquiry thanks.aspx?did=90"
"/find-enquiry thanks.aspx?did=38"
"/future-contact thanks.aspx"
If the URL = true then I will attach tracking to that URL. In VB.net the contains() or a binary search could be used but with JS I am stuck.
Did you mean based on the current URL? You want something like this maybe:
function check(url, paths) {
return !!paths.find(function (path) {
return url.indexOf(path) !== -1;
});
}
var paths = [
"/find-enquiry-thanks.aspx?did=62",
"/find-enquiry thanks.aspx?did=90",
"/find-enquiry thanks.aspx?did=38",
"/future-contact thanks.aspx",
];
if (check(window.location.href, paths)) {
//do stuff
}
Note, Array.prototype.find
is new and not all browsers have it so if you want what it does you might want to look at lodash/underscore _.find
or just make a messy for loop that returns:
function check(url, paths) {
for (var i = 0; i < paths.length; i++) {
if (url.indexOf(path) !== -1) {
return true;
}
}
return false;
}
Try something like this:
(function(){
var pageUrl = window.location.href;
var urls = ["/find-enquiry-thanks.aspx?did=62","/find-enquiry-thanks.aspx?did=90","/find-enquiry-thanks.aspx?did=38","/future-contact-thanks.aspx"];
for (var i = 0; i < urls.length; i++){
if (pageUrl.indexOf(urls[i]) > 0){
document.write('valid url');
}
}
})();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.