Get query string parameters from href in a tag
<p>I have a page with a series of <code>&lt;a&gt;</code> links on it that look like this:</p>

<pre><code>&lt;a href="http://www.domain.com/page/other.jsf?fruit=apple&amp;tree=pine&amp;rock=sedimentary"&gt;click me&lt;/a&gt;
</code></pre>

<p>These parameters manipulate the content for the eventual page linked to ("other.jsf") in minor ways.</p>

<p>As part of an A/B/n test I want to change the parameters in the href based on user behaviour on the page containing the link. So, for example, I'd want to change the fruit parameter to "orange" before it was clicked.</p>

<p>My problem is that the parameters change location in the string or may not exist at all for some links and the .param() function only appears to work on urls.</p>

<p>So far (based on another question answer) I have this, but it doesn't account for the possibility that there may be no "end_pos" or if "fruit=" is missing from the href (though this second bit seems like an easier fix with an if undefined-type function):</p>

<pre><code>$('a').each(function () {
    if ($(this).attr('href').indexOf('other') &gt; -1) {
        var hrefStr = $(this).attr('href');
        var start_pos = hrefStr.indexOf('fruit=') + 1;
        var end_pos = hrefStr.indexOf('&amp;',start_pos); //works as long as fruit=apple is in the middle or front of the string
        var fruit = hrefStr.substring(start_pos,end_pos);
        ...
        //put modified href back in &lt;a&gt;
    }
});
</code></pre>

<p>My second problem is then identifying the same part of the original href to put the new string back into. I can probably get this after understanding the method for extracting it in the first place though.</p>

<p>I should also say I have no control over the .jsf pages other than via JavaScript</p>