rusya_sk rusya_sk - 5 months ago 27
Javascript Question

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 shown. If params are empty or URL don't have params then block with id="default-content" will shown.

And there is a question: i need that parametr in URL (utm_term) was not equal some word, but just content it.

Because now if URL have utm_term=smth_buy, i will see default-content.

Answer

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)