John P.
John P.

Reputation: 35

capture data based on the values in URL

Is there a way to write a function in JS, if URL contains utm_campaign value, then send it, otherwise leave it blank.

For example i have this link.

http://example.com/home/?utm_campaign=mycampaign_2016_en&utm_medium=cpc&utm_source=google&utm_content=home

I want my function to return "campaign_2016_en" in my script. And when the utm_campaign parameter is not available return blank. But note that the URL and the values would not be the same always.

I am not sure where to start. Appreciate all the helps.

Upvotes: 0

Views: 46

Answers (1)

Rajesh Kumar
Rajesh Kumar

Reputation: 471

You can try this:

    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, " "));
    }

Call above function, this function will return empty string if query string value is not available.

getParameterByName('utm_campaign', 'http://example.com/home/?utm_campaign=mycampaign_2016_en&utm_medium=cpc&utm_source=google&utm_content=home');

Or just pass query string param name. It will use window object to read url

getParameterByName('utm_campaign');

JS Fiddle:

https://jsfiddle.net/wx38rz5L/4199/

Upvotes: 2

Related Questions