George Milonas
George Milonas

Reputation: 563

JavaScript URL Compare with WildCard

Hey guys I have a project where I need to trigger a function on specific pages.

Users would input something like:

var dexiTriggerPages = "/user/*/register, /user/*/pay";

If the current url matches the wildcard url, the function should trigger a conversion. The url can't contain another path after the given paths. Currently my current code is not working at all.

// Trigger Conversions for Specific Pages
if(dexiTriggerPages.trim() != '')
{
    var urls = document.deximedia.explode(',',dexiTriggerPages);

    for (var i=0;i<urls.length;i++)
    { 
        var url = urls[i];
        if(url.indexOf("*") != -1)
        {
            var pass = true;

            var segments = document.deximedia.explode('*',url); 
            for (var i=0;i<segments.length;i++)
            { 
                if(document.URL.indexOf(segments[i]) == -1)
                {
                    pass = false;
                }
            }
            if(pass)
                document.deximedia.dexiTriggerConversion();
        }
        else
        {
            if(document.URL.indexOf(url) != -1)
            {
                document.deximedia.dexiTriggerConversion();
            }
        }
    }
}

Any help on getting this to work would be greatly appreciated!

Upvotes: 0

Views: 547

Answers (2)

George Milonas
George Milonas

Reputation: 563

I was able to solve the problem by using the following:

// Trigger Conversions for Specific Pages
if(dexiTriggerPages.trim() != '')
{
    var urls = document.deximedia.explode(',',dexiTriggerPages);
    var pathArray = document.deximedia.explode('/',window.location.pathname.replace(/^\/|\/$/g, ''));

    for (var i=0;i<urls.length;i++)
    { 
        var url = urls[i].trim().replace(/^\/|\/$/g, '');
        var urlPaths = document.deximedia.explode('/',url);
        if(pathArray.length == urlPaths.length)
        {
            var pass = true;
            for (var a=0;a<pathArray.length;a++)
            {
                if(pathArray[a] != urlPaths[a] && urlPaths[a] != '*')
                    pass = false;
            }
            if(pass == true)
                document.deximedia.dexiTriggerConversion();
        }

    }
}

Upvotes: 0

Mark
Mark

Reputation: 2221

Would you be willing to use regular expression to do this?

(^/user/(.*)/register$|^/user/(.*)/pay$)

You can test it out on this website

Upvotes: 1

Related Questions