Search code examples
jqueryconditional-statementshref

Append string to url based on condition using jQuery


I'm trying to figure out how to add either ?ref=xyz or &ref=xyz depending on whether a question mark is already part of the url (?ref=xyz if no ? is present, or &ref=xyz if there is a ? in the URL)

Here's what I'm trying to do without success, can anyone help me write code that will test for both conditions and append the appropriate string to the end of the URL please?

$('a[href*="domainname"]').attr('href', function(index, attr) {
    if([doesn't contain ?]) {
        return attr + '?ref=xyz';
    } else if([contains ?]) {
        return attr + '&ref=xyz';
    }
});

Thanks,

Osu


Solution

  • Use indexOf JavaScript method. Try this.

    $('a[href*="domainname"]').attr('href', function(index, attr) {
        if(attr.indexOf('?') == -1) {
            return attr + '?ref=xyz';
        } else{
            return attr + '&ref=xyz';
        }
    });