Reputation: 417
I'm looking to extract some of the utm values from a URL using regexp. My URL would look something like the below -
utm_source=ko_1d5b57661294a3154&utm_medium=internetq&utm_campaign=-android5436af9f1aef91a654a7255038&utm_term=searchthis&utm_content=mainpage&
Is there any way to have a regexp that would extract all the utm values such as utm_source, utm_medium, utm_capaign, utm_term, utm_content ?
Upvotes: 1
Views: 4156
Reputation: 7476
Here i am what i am doing is getting every value between = and & sign.
/[^=]\w+(?=&)/g
Another one according to utm_
/[^utm_=]\w+(?=&)/g
Upvotes: 0
Reputation: 10909
You could grab all patching pairs and then convert it to an object.
NOTE: The object conversion is simplistic (doesn't account for multiple params of the same key, etc.).
var regexp = /(?!&)utm_[^=]*=[^&]*(?=&)/g;
var query = 'utm_source=ko_1d5b57661294a3154&utm_medium=internetq&utm_campaign=-android5436af9f1aef91a654a7255038&utm_term=searchthis&utm_content=mainpage&';
var matches = query.match(regexp);
var values = matches.reduce(function(obj, param) {
var keyVal = param.split('=');
obj[keyVal[0]] = keyVal[1];
return obj;
}, {});
document.write('<pre>' + JSON.stringify({
matches: matches,
values: values
}, null, 2) + '<pre>');
Upvotes: 2
Reputation: 445
You could use a positive lookbehind for this case. The pattern would look like that:
(?<=utm_[a-z]+=)\w+
This pattern matches any alphanumerical characters that are preceeded by "utm_???="
Upvotes: 1