-1

I have a code that generates text depending on variables in the url. What I want to know is if there a method to get two variables that are located separately from each other in the same string of the url at the same time to show my text.

Say this is my string ?q1=iphone3gs&q2=Other&q3=fixme. The url must contain iphone and other in order for the text to show.

iphone and other must be selected to show text http://jsfiddle.net/2tXvh/6/show/?q1=iphone3gs&q2=Other&q3=fixme (this is only calling on q2=Other)

I was think along the lines of using (/iphone&Other/) shown below but that will not work.

if (keys[1].match(/iphone&Other/)) {
    $("#linkdiv1").append(nextLink1);
}
  • Dup? http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript – elclanrs May 25 '14 at 23:16
  • @elclanrs No. I am asking to get two variables at the same time to dispay the text. –  May 25 '14 at 23:18

1 Answers1

0

That's not how regex works. If you want to match 2 things together, you're going to have to either use 2 regexes (if you want to make sure it's in seperate order), or specify what is allowed to be in between the 2 matched strings. In this case, you'll probably need 2 seperate matches:

if (keys[1].match('iphone') && keys[1].match('Other')) {
    $("#linkdiv1").append(nextLink1);
}

Or, since you're simply searching for the occurrence of a string, you don't need to use a regex, or .match() for that matter:

if (keys[1].indexOf('iphone') !== -1 && keys[1].indexOf('Other') !== -1) {
    $("#linkdiv1").append(nextLink1);
}
Joeytje50
  • 18,636
  • 15
  • 63
  • 95
  • "If you want to match 2 things, you're going to have to either use 2 regexes" -- Why? How about capture groups? `match` returns an array. If you're just going to "match" you might as well `test`. – elclanrs May 25 '14 at 23:17
  • @elclanrs so would you recommend `keys[1].match(/iphone|Other/g).length == 2` then? That wouldn't work, because it might just match `iphone` twice. In this case, you need 2 regexes. – Joeytje50 May 25 '14 at 23:19
  • @elclanrs okay, I've edited it: it now says "If you want to match 2 things **together**, ...". Anyway, if you have a better solution than mine, please post it as an answer. For now though, this solution works just fine. – Joeytje50 May 25 '14 at 23:21
  • Maybe something like `if (/(?=iphone).*(?=Other)/.test(keys[1]))`, but that sort of assumes the order is kept, which might not be the case. I would really do this by extracting the params q1, q2... and loop and compare on a real data structure. – elclanrs May 25 '14 at 23:25