Parse only one query string parameter into a 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 only the q parameter value in an array with javascript or jquery?

I need an array like this

 ['how', 'can', 'i', 'get', 'this'] 
+5
source share
3 answers

Assuming that the order of your query strings will not always be known, and that you need to support a q search 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; } } 
+2
source

Your question really is a combination of a series of questions that everyone must answer in order to proceed to the next part.

You asked how to pull the q parameter from the query string and divide it into spaces, but this does not take into account the fact that you need to parse the URL first.

Part 1: Parse URL Analysis

You noted that completely 100% is not required . However, this suggests that you are working in a browser environment and not on the server side, which means that we can use several tricks to parse URLs that are not available in .

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

If you have a URL string and want a query string, you can use the a element to parse automatically. Refer to the anatomy link to find out which parts of the URL are:

 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 is worth noting that the specified url ( www.example.com/yy?q=how+can+i+get+this&o=1&source=home ) is incorrect and the protocol is missing, which means that its parsing will lead to that pathname will be considered 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 a query string in parts

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

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

My recommendation is not to reinvent the wheel . I wrote a QueryString parser , which is available with a MIT license, or if you don’t like my attempt at a solution, consider using the querystring module from , which is available with .

The module that I wrote myself uses UMD, so it should be compatible with most projects, regardless of what you use (or not use) to manage communications and dependencies.

 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: Break a line into spaces

This part is deceptively simple. It would be easy to say that you are using:

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

But this is most likely not what you want. If you also want to split into tabs or newlines, this will be more complicated. You probably also want to avoid empty lines in the array ( ' foo bar ' will have 3 empty lines). Without knowing your intention, it is difficult to recommend a course of action. As a rule, splitting using a regular expression along the lines /\s+/g and then filtering out any possible starting and ending empty lines is a more robust 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 lot of work, and it is. Unfortunately, JS does not have much support for some of these commonly used features. UrlSearchParams has partial browser support, but even this one has problems parsing query strings.

Just make sure that you handle each of these parts correctly, otherwise the user can simply change the URL to your page and most likely will come across in an unexpected way.

+1
source

Try using String.prototype.match() in the str input line, with the RegExp argument /q=\w+.*/ to match the line starting with "q=" ; call .split() on the string element at index 0 returned array from .match() with the RegExp parameter /q=|&.*|\+|#|%20/ ; call .filter() to remove empty elements from the array returned by .split()

 var res = str.match(/q=\w+.*/)[0].split(/q=|&.*|\+|#|%20/).filter(Boolean); 

 var str = "www.example.com/yy?q=how+can+i+get+this&o=1&source=home"; var res = str.match(/q=\w+.*/)[0].split(/q=|&.*|\+/).filter(Boolean); document.write(JSON.stringify(res)); 
0
source

All Articles