Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse just one query string parameter into Javascript array

I have this query string www.example.com/yy?q=how+can+i+get+this&o=1&source=home

How can I parse just the q parameter value in a array with javascript or jquery ?

I want the array like this

['how', 'can', 'i', 'get', 'this']
like image 532
Hayi Avatar asked Sep 27 '22 20:09

Hayi


2 Answers

Assuming that the order of your query strings aren't always going to be known and that you have to support finding 'q' anywhere;

// substring(1) to skip the '?' character
var queryStrings = window.location.search.substring(1).split('&');
var qArray;
for (var i = 0; i < queryStrings.length; i++) {
  if (queryStrings[i].substring(0, 2) === 'q=') {
    qArray = queryStrings[i].substring(2).split('+');
    break;
  }
}
like image 109
diadical Avatar answered Oct 06 '22 19:10

diadical


Your question really a combination of a series of questions that each need to be answered to move to the next part.

You asked how to pull the q parameter out of the query string and split it on spaces, but this overlooks the fact that you first need to parse the URL.

Part 1: Parsing a URL Into Parts

You tagged jquery, which is completely 100% unnecessary. However, this does tell me that you're working in a browser environment rather than server-side JavaScript, which means that we can use a few tricks to parse URLs that aren't available in node.

If you know you want to get the query string from the current URL, you can simply access location.search

If you have a URL string and you want to get the query string, you can use an a element to do the parsing automatically for you. Refer to link anatomy to see which parts of the URL are which:

function parseUrl(url) {
  var a = document.createElement('a');
  a.href = url;
  return {
    href: a.href,
    protocol: a.protocol,
    host: a.host,
    hostname: a.hostname,
    port: a.port,
    pathname: a.pathname,
    search: a.search,
    hash: a.hash
  };
}

At this point it's worth noting that the url given (www.example.com/yy?q=how+can+i+get+this&o=1&source=home) is malformed, and missing the protocol, which means that parsing it will result in the pathname being treated as a relative path from the current URL. To fix this, prefix the URL with http://:

var parts = parseUrl('http://www.example.com/yy?q=how+can+i+get+this&o=1&source=home');
var search = parts.search;

function parseUrl(url) {
  var a = document.createElement('a');
  a.href = url;
  return {
    href: a.href,
    protocol: a.protocol,
    host: a.host,
    hostname: a.hostname,
    port: a.port,
    pathname: a.pathname,
    search: a.search,
    hash: a.hash
  };
}
var parts = parseUrl('http://www.example.com/yy?q=how+can+i+get+this&o=1&source=home');
console.log(parts);

Part 2: Parsing the Query String Into Parts

This part is easy to mess up because query strings are hard (full disclosure, I wrote that blog post).

Anyone attempting to parse a query string using a regular expression is probably wrong in many ways.

My recommendation is don't reinvent the wheel. I wrote a QueryString parser, which is available with an MIT license, or if you're not comfortable with my attempt at a solution, consider using the querystring module from node, which is available with browserify.

The module I wrote myself uses UMD, so it should be compatible with most projects regardless of what you're using (or not using) for bundling and dependency management.

var qs = new QueryString({
  flatten: true,
  semicolons: false
});
console.log(qs.parse('?q=how+can+i+get+this&o=1&source=home'));
<script src="https://cdn.rawgit.com/zzzzBov/QueryStringJS/master/dist/querystring.min.js"></script>

Part 3: Splitting a string on spaces

This part is deceptively easy. It would be easy to tell you to use:

'how can i get this'.split(' ');

But that's likely not actually what you want. If you want to also split on tabs, or newlines, it's more complicated. You probably also want to avoid empty strings in the array as well (' foo bar ' would have 3 empty strings). Without knowing your intention, it's hard to recommend a course of action. Generally, splitting using a regular expression along the lines of /\s+/g and then filtering any possible leading and trailing empty strings is a more resilient solution:

var arr = 'how can i get this'.split(/\s+/g).filter(function (v) {
  return v;
});

Part 4: All Together Now

var parts,
    qs,
    queryString,
    arr;

function parseUrl(url) {
  var a = document.createElement('a');
  a.href = url;
  return {
    href: a.href,
    protocol: a.protocol,
    host: a.host,
    hostname: a.hostname,
    port: a.port,
    pathname: a.pathname,
    search: a.search,
    hash: a.hash
  };
}

parts = parseUrl('http://www.example.com/yy?q=how+can+i+get+this&o=1&source=home');
console.log('parts', parts);

qs = new QueryString({
  flatten: true,
  semicolons: false
});
queryString = qs.parse(parts.search);
console.log('query string', queryString);

arr =
  (queryString.q || '')
    .split(/\s+/g)
    .filter(function (v) {
      return v;
    });
console.log('array', arr);
<script src="https://cdn.rawgit.com/zzzzBov/QueryStringJS/master/dist/querystring.min.js"></script>

Now this may seem like a bunch of work, and it is. It's unfortunate that JS doesn't have a lot of native support for some of these commonly used features. UrlSearchParams has partial browser support, but even that has issues parsing query strings.

Just be sure that you're handling each of these pieces correctly, otherwise a user can simply change the URL to your page and likely have it crash in unexpected ways.

like image 35
zzzzBov Avatar answered Oct 06 '22 19:10

zzzzBov