Youssef Youssef - 3 months ago 12
jQuery Question

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']

Answer

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;
  }
}