0

I am trying to check if the current url

base_url/index.php?name0=value0&name1=value1&name2=value2...

contains a specific name=value. I tried this

var path = $.inArray('name=value', $(location).attr('href').split('&'));
        if (path  > -1){ triggers my function...}

But I guess that this wouldn't work if the url is url encoded. Is there a way to check if the url contains name=value without checking all the conditions (split('&') or split('%26')) ?

doelleri
  • 19,232
  • 5
  • 61
  • 65
user1611830
  • 4,749
  • 10
  • 52
  • 89

2 Answers2

1

You can use core javascript for this:

var parameterName = 'name0';
var parameterValue = 'value0';
var path = decodeURI(location.href).indexOf(parameterName+'='+parameterValue); 
if (path > -1){ 
    triggers my function...
}

EDIT: I've tested it more and neither solution is perfect: mine fails when you have something before the specified name value, for example: varname0 when you check name0 will be found and that's not correct, yours (and monshq's) doesn't check the first value/pair which follows ? character.

How can I get query string values? is something you're looking for.

Community
  • 1
  • 1
AlecTMH
  • 2,615
  • 23
  • 26
1

Split will always work, because & part of url is not encoded if it split parameters. However, you can have name or value encoded in the url. To search for them, you should use encodeURI like that:

var path = $.inArray(encodeURI('name=value'), $(location).attr('href').split('&'));
    if (path  > -1){ triggers my function...}
monshq
  • 343
  • 2
  • 11