Search code examples
jqueryurldynamicparametersutm

Dynamic content depending url params


I have that jquery script:

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

var dynamicContent = getParameterByName('utm_term');

 $(document).ready(function() {

            if (dynamicContent == 'buy') {
        $('#buy').show();
    }

    else {
        $('#default-content').show();
    }
});

It's working like this: if utm_term param in URL equal 'buy' then block with id="buy" will show. If params are empty or URL don't have params then block with id="default-content" will show.

And there is a question: I need that parameter in URL (utm_term) not equal some word, but just have it.

Because now if URL have utm_term=smth_buy, I see #default-content, and I would see #buy.

Any ideas?


Solution

  • Maybe you should use a regexpr:

    if (dynamicContent.match(/buy/)) {
        $('#buy').show();
    }
    
    else {
        $('#default-content').show();
    }
    

    If you want it case insensitive:

    if (dynamicContent.match(/buy/i)) {
        $('#buy').show();
    }
    
    else {
        $('#default-content').show();
    }
    

    (i flag sets the pattern case insensitive, bUY will match same as BUY)