1

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

1 Answer 1

2

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';
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Fantastic, I just neeed to update the second part of the expression, works a treat. Need to wait 9 mins to approve the answer, but thank you!
@Osu - Edited my answer, else part doesn't need any condition.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.