Skip to content

Implement hasQuery/hasSearch to check for query parameters #71

Closed
EnTeQuAk opened this Issue Mar 4, 2013 · 2 comments

2 participants

@EnTeQuAk
EnTeQuAk commented Mar 4, 2013

It would be nice to have a very simple helper to check for existing/matching query parameters, except I missed something in the code :-D

My approach for now, I was not sure if it makes sense to implement the same argument structure as in add/remove Query.

@@ -551,6 +551,24 @@ URI.removeQuery = function(data, name, value) {
         throw new TypeError("URI.addQuery() accepts an object, string as the first parameter");
     }
 };
+URI.hasQuery = function(data, name, value) {
+    var i, length, key;
+
+    if (!typeof name == "string") {
+        throw new TypeError("URI.hasQuery accepts a string as first parameter");
+    }
+
+    if (typeof name == "string") {
+        if (value !== undefined && data[name] === value) {
+            return true
+        } else if (value === undefined && name in data) {
+            return true
+        }
+    }
+
+    return false;
+};
+

 URI.commonPath = function(one, two) {
     var length = Math.min(one.length, two.length);
@@ -1293,9 +1311,14 @@ p.removeQuery = function(name, value, build) {
     this.build(!build);
     return this;
 };
+p.hasQuery = function(name, value, build) {
+    var data = URI.parseQuery(this._parts.query);
+    return URI.hasQuery(data, name, value);
+};
 p.setSearch = p.setQuery;
 p.addSearch = p.addQuery;
 p.removeSearch = p.removeQuery;
+p.hasSearch = p.hasQuery;

 // sanitizing URLs
 p.normalize = function() {
@rodneyrehm
Medialize member

Your value test doesn't quite cut it yet:

  • the value could be an array ?foo=1&foo=2 is parsed to {foo: ["1", "2"]} and a strict equality won't do it, as ["a"] !== ["a"]
  • the parser always returns strings, so URI("?foo=1").hasQuery("foo", 1) === false because of that strict equality

value should probably also be treated as a callback function to allow custom comparison.

@EnTeQuAk
EnTeQuAk commented Mar 4, 2013

Ah, okay. Thanks @rodneyrehm for the review, I'll change that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.