We add link tracking in our outbound links in the URL strings, which is based on a global variable that's declared on the page, but need the ability to modify only one of the links to read a different value. For example, in the sample below, all links for Ask, Bing, Duck Duck Go, and Yahoo, should be appended with the value "webcampaign", such as this:
http://www.ask.com/?group=&placement=webcampaign
http://www.bing.com/?group=&placement=webcampaign
http://www.duckduckgo.com/?group=&placement=webcampaign
http://www.yahoo.com/?group=&placement=webcampaign
However, we need Google to read like this:
http://www.google.com/?group=&placement=defLink
Here's the challenge. How can I modify the JavaScript so that the Google link reads differently than the rest of the links?
Here's a simple example where all links would have the same URL string appendage:
<html>
<head>
<title>Dynamic Link Test</title>
<script>
var placement = "webcampaign";
</script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="globalscripts_plain.js"></script>
</head>
<body>
<p><a href="http://www.ask.com">Ask</a></p>
<p><a href="http://www.bing.com">Bing</a></p>
<p><a href="http://www.duckduckgo.com">Duck Duck Go</a>
<p><a href="http://www.google.com" id="defLink">Google</a></p>
<p><a href="http://www.yahoo.com">Yahoo!</a></p>
</body>
</html>
Here's the script that appends each link with the placement variable, which is declared at the top of the markup:
(function($, undefined) {
var App = (window.App || (window.App = {}));
$.extend(App,{
getParameterByName : function (name) {},
});
$(function() {
$('a[href^="http"]').each(function() {
var $a = $(this),
q = $a.attr('href') ? $a.attr('href').indexOf('?') : -1,
contents = $a.html();
if (q == -1) {
$a.attr('href', $a.attr('href') + '?group=' + '&placement=' + placement);
} else {
$a.attr('href', $a.attr('href') + '&group=' + '&placement=' + placement);
}
});
});
})(window.jQuery);
JSFiddle link: https://jsfiddle.net/Codewalker/v92L8pbw/1/
RegExpon the.attr('href').