0

I'm trying to use javascript to complete something that i've done a ton of times in PHP.

I have two instances of urls that come into my site. One from a tracking link... and another from search or share, so on...

tracking link: www.foo.com/blog?offer=pine&sub_id=123 non paid search link: www.foo.com/blog

I'd like to detect if my link has a string, and if so pass the offer into a url within the page. In PHP i'd do this like so.

<?php
    if(array_key_exists('sub_id', $array)) {
        $my_variable = $array['sub_id'];
    } else {
        $my_variable = 'my default value';
    }
?>
    <a class="submitbutton" href="www.joinmywebsite.com/join?offer=pine&sub_id=<?php echo $my_variable; ?>">Join My Site</a>

Is it possible to do this with javascript? I've search and search and ever function I find either returns the value of the string parameter or it sees nothing and does nothing.

Thanks.

2 Answers2

0

Sure:

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(
                                                results[1].replace(/\+/g, " "));
}

var subId = getParameterByName('sub_id') || 'my default value';

$(function(){

     $('a.submitbutton')
       .prop({ href: 'www.joinmywebsite.com/join?offer=pine&sub_id=' + subId  });
});

Source: How can I get query string values in JavaScript?

Community
  • 1
  • 1
Johan
  • 35,120
  • 54
  • 178
  • 293
0

If I understand your question, this should be the answer:

<script type='text/javascript'>
function getUrlVars()
{
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { vars[key] = value; });

    return vars;
}


var path = window.location.href;
var position = path.indexOf("sub_id");

if (position != -1)
    var desired = getUrlVars()["sub_id"];
else
    var desired = 'my default value';

//alert(desired);
</script>

<a class="submitbutton" onClick="document.location.href='http://www.joinmywebsite.com/join?offer=pine&sub_id=' + desired;">Join My Site</a>
Hertz
  • 29
  • 4