Peter Svitly Peter Svitly - 6 months ago 9
Javascript Question

Function for URL doesn't return correct value

I'm using 2 functions in my webshop to Auto set the

href
in my anchor tag

This is what they look like before the script :

<a class="Motifyer" data-query="Brand" data-value="@brand.Item1" href="#">
<a class="Motifyer" data-query="Brand" data-value="@brand.Item1" href="#">


And after the query :

<a class="Motifyer" data-query="Brand" data-value="@brand.Item1" href="http://localhost:44300/shop?Brand=Apple">
<a class="Motifyer" data-query="Brand" data-value="@brand.Item1" href="http://localhost:44300/shop?Brand=Samsung">


The smart think is (according to me) if the url contains
Brand=Samsung
the result would be:

<a class="Motifyer" data-query="Brand" data-value="@brand.Item1" href="http://localhost:44300/shop?Brand=Apple">
<a class="Motifyer" data-query="Brand" data-value="@brand.Item1" href="http://localhost:44300/shop">
<!-- Notice the removed query on the second one -->





The problem is that if I have multiple params in my query and if I remove the first
?xxx=xxx
, it sometimes dont change the first & into an ?

Can someone tell me where the problem might be?

The following code contains my JS functions :

$('.Motifyer').each(function () {
var url, query, value, queryCount, matches;

url = window.location.href.replace("#", "");
query = $(this).data('query');
value = $(this).data('value');
matches = url.match(/[a-z\d]+=[a-z\d]+/gi);
queryCount = matches ? matches.length : 0;

if (url.indexOf(query) > -1) {
if (getParameterByName(query) == value) {
url = url.replace("?" + query + "=" + value, "");
url = url.replace("&" + query + "=" + value, "");
} else {
url = url.replace(query + "=" + getParameterByName(query), query + "=" + value)
}

} else {
if (queryCount == 0) {
url = url + "?" + query + "=" + value;
} else {
url = url + "&" + query + "=" + value;
}
}
$(this).attr("href", url);
});

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

Answer

The code looks fine to me, this might work as a "quick" solution for your.

Insert this line: url = url.replace("?" + query + "=" + value + "&", "?");

if (url.indexOf(query) > -1) {
    if (getParameterByName(query) == value) {
        ----> Insert Right here <----
        url = url.replace("?" + query + "=" + value, "");
        url = url.replace("&" + query + "=" + value, "");
    } else {
        url = url.replace(query + "=" + getParameterByName(query), query + "=" + value)
    }

} else {
    if (queryCount == 0) {
        url = url + "?" + query + "=" + value;
    } else {
        url = url + "&" + query + "=" + value;
    }
}