0

Could anybody have a suggestions on how to simply detect whether a string "looks like" a query string or not? For example, if I had a query string like this:

field1=value1&field2=&field3=value4

it would return true.

Here's what I'm thinking should do the trick for what I need, but I am also open to any other suggestions as well as the below is very sketchy. Maybe there's even a function that returns false when parsing an invalid query string?

function looks_like_querystring(source) {
    return /=.*?&/g.test(source);
}

or

function looks_like_querystring(source) {
    return source.indexOf('&') != -1 && source.indexOf('=') != -1;
}
Andrew T.
  • 4,701
  • 8
  • 43
  • 62
Rick
  • 712
  • 5
  • 23
  • Just in case, both of your methods return `false` when I tested it with a valid `field1=value1` query string. Do you have more specification that the query string must always have '&'? Perhaps reading [corresponding Wikipedia article](http://en.wikipedia.org/wiki/Query_string) could help understanding more about the rule for valid query string. – Andrew T. Sep 24 '14 at 01:53
  • Good question, but in my case there will always be many parameters. Will never contain "?" and may or may not begin with "&".. I know there's really no sure fire way to do this, I'm just trying to get a decent check.. Maybe could add in that it cannot start with "<, {, [". – Rick Sep 24 '14 at 02:03
  • Put that info to the question body, and perhaps if possible, more test cases to clarify the problem. – Andrew T. Sep 24 '14 at 02:07

2 Answers2

0
String.prototype.isInvalidCharacter=function(){
    validCharacters="1234567890qwertyuiopasdfghjklzxcvbnm&="
    for(var i in validCharacters){
        if (validCharacters[i]===this.valueOf()) return false;
    }
    return true;
}

String.prototype.isQueryString=function(){
    for(var i=0;i<this.length;i++){
        if (this[i].isInvalidCharacter()){return false;}
    }
    var prevChar="&";
    var counter=0;
    for(var i=0;i<this.length;i++){
        if (this[i]==="="){
             if(prevChar==="=") return false;
             prevChar="=";counter++;
        }
        if (this[i]==="&"){
            if(prevChar==="&") return false;
            prevChar="&";counter++;
        }
    }
    if (counter===0) return false;
   return true;
}
Nick Manning
  • 2,828
  • 1
  • 29
  • 50
0

Thanks all.. Got a bit tied up yesterday but ended up just going with a regex based off of what I found here after I had posted this question: Validate URL query string with regex

Here's what I ended up using that works perfectly for my purpose:

function looks_like_querystring(source) {
    return /^\???[^<[{]([^=&?]+(=[^=&?]*)?(&[^=&?]+(=[^=&?]*)?)*)?$/.test(source);
}
Community
  • 1
  • 1
Rick
  • 712
  • 5
  • 23