JavaScript Query String Getting and Parsing to Object with Regular Expression

What is Query String

Query string is the part of a uniform resource locator (URL) containing data that does not fit conveniently into a hierarchical path structure. It commonly includes fields (requested pairs of key and value) added to a base URI by a Web browser or other client application, for example

The first delimiter between the requested file name and the starting parameters is question mark ? while the parameters are separated by the & character. The query string is the input parameters to the dynamic pages, therefore dynamic pages such as PHP, JSP or ASP.NET can process these parameters using similar GET or Request global variables to fetch these key pairs.

Getting Query String

Here question mark ? is our main delimiter to separate the base URI/requested file with the starting parameters. The part of url before question mark ? will be removed by replacing empty string with with regular expression

Parsing Query String to Object

Instead of using split function to convert the query string as array, parsing the query string to standard json format string with regular expression is our solution here:

The parsing steps are as below:

  1. Decode URI decodeURIComponent(url)
  2. Get query string from decode URI with regular expression
  3. Parse query string to standard JSON format string with regular expression
  4. Convert the JSON format string to JSON object with JSON.parse() function

ScreenShot for executing the code in browser console:

Leave a Reply

Your email address will not be published. Required fields are marked *