November 11, 2014 · javascript

How to get url parameters javascript

This is simple function for extraction of query string parameters. I think that code is self explanatory.

 function p(p) { console.log(p); }

 var testQueries = [
     "https://www.google.com/search?sugexp=chrome,mod=1&sourceid=chrome&ie=UTF-8&q=how+to+get+url+params",
     "https://www.google.com/search?sugexp=chrome,mod=1&sourceid=chrome&ie=UTF-8&q=extract+query+string+javascript"
 ];

 function split(query) {
     var queryString = {};

     var parts = extractQueryString(query, extractQueryStringRegular);

     if (!parts) {
         parts = extractQueryString(query, extractQueryStringHashed);
     }

     if (!parts) return null;

      var queryStringPairs = parts[1].split("&");

     if (queryStringPairs.length == 1 && queryStringPairs[0] === "") {
          return null;
      }

      for (var i = 0, len = queryStringPairs.length; i < len; i++) {
           var qm = queryStringPairs[i].indexOf("=");
           if (qm < 0) {
             queryString[queryStringPairs[i]] = "";
             continue;
           } 
           var queryItem = [queryStringPairs[i].slice(0,qm), queryStringPairs[i].slice(qm+1)];
           var queryName = decodeURIComponent(queryItem[0]);
           var queryValue = decodeURIComponent(queryItem[1]);
           if (queryName.length) {
             queryString[queryName] = queryValue;    
           }
      }

      return queryString;
 }

 function extractQueryString(query, splitterFn) {
     if (null == query || undefined == query)
         return null;

     var result = splitterFn(query);

     if (result.length != 2) {
         return null;
      }

      return result;
 }

 function extractQueryStringHashed(query) {
     return query.split("#");
 }

 function extractQueryStringRegular(query) {
     return query.split("?");
 }

 for (var i = 0, len = testQueries.length; i < len; i++) {
     var result = split(testQueries[i]);
     p(result);  
 }

Result

Follow me on Twitter

  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket
Comments powered by Disqus