5

I currently have this bit of jQuery I am using to append a URL with some location information.

jQuery('a').attr('href', function() {
            return this.href + "&location=/123/abc";
       });

My issue is most links have a ? in which makes for the use of the above & ok. There are a select few that dont. I am looking to check the url to see if there is a ?. If there is I want to use "&location=/123/abc", if there is no ? I will need to use "?location=/123/abc"

I am not the best with if/else statements. Any help would be appreciated.

if (thereIsA?InTheUrl) {

    return this.href + "&location=/123/abc";

} else {

    return this.href + "?location=/123/abc";

}

Something like that, just not sure oh to write it.

Francisc
  • 72,090
  • 61
  • 175
  • 271
Michael
  • 434
  • 6
  • 19

4 Answers4

7
   jQuery('a').attr('href', function() {
        return (this.href.indexOf("?") >= 0) ? this.href + "&location=/123/abc" : this.href + "?location=/123/abc";
   });
mynameiscoffey
  • 14,174
  • 5
  • 32
  • 44
1

Michael.

Use JavaScript's indexOf() function.

Like this:

if(this.href.indexOf('?')>=0){//PLACE MAGIC HERE}

How it works is this:

Returns position of matched string if it finds it.
Returns -1 if it does not find it, hence >=0. Position 0 is the first character of a string.

Details here:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/indexOf

Francisc
  • 72,090
  • 61
  • 175
  • 271
  • 1
    This works. Same as accepted answer above, just with less detail. I selected the answer above so other people learning can understand the process. Thanks you. – Michael Jun 13 '11 at 23:11
1
var str = window.location.href;
if (str.indexOf('?' >= 0) {
  return str + "&location=/123/abc"; //there's a ?
} else {
  return str + "?location=/123/abc"; //no ?
}
Jason
  • 49,989
  • 37
  • 128
  • 183
0
if (this.href.indexOf("?") >= 0)
xyz-123
  • 2,145
  • 4
  • 20
  • 26
  • This works. Same as accepted answer above, just with less detail. I selected the answer above so other people learning can understand the process. Thanks you. – Michael Jun 13 '11 at 23:11