0

Hello guys! I try to accomplish the following. I have a string which is a query string like:

let query = "?course_subject=Robotica&course_type=%20C&course_location=%20VIV7&course_teacher=%20Pozna_C_R&course_start_hour=14:00%20&course_end_hour=%2015:50"

Which I get with:window.location.search

What I try to get back is all the pairs name - value in an array like:

output_array = [["course_subject","Robotia"],["course_type","C"]]

And so on. But I can not figure out how to write the code using regex. Can someone help me with the code? I mention that I do not know the query string which it will come, so I can not search using a name,like:course_subject or course_type

  • Possible duplicate of [How can I get query string values in JavaScript?](https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) Have you taken a look [here](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams). (this is the link provided by the top answer in the question above. I think the for-of example solves your problem. – DoloMike Dec 05 '17 at 17:34

3 Answers3

0
let query = "?course_subject=Robotica&course_type=%20C&course_location=%20VIV7&course_teacher=%20Pozna_C_R&course_start_hour=14:00%20&course_end_hour=%2015:50"    
var output_array=[];
    decodeURI(query.slice(1)).split("&").forEach(function (item) {
        output_array.push(item.split("="));
    });

should do the job. slice(1) is for getting rid of ? at the start.

0

No need to use regex.

First you need to decode uri (https://www.w3schools.com/jsref/jsref_decodeuri.asp)

let loc = decodeURI(window.location.search);

Then you have to remove first character and split string with '&'

loc = loc.substring(1).split('&');

This will give you something like this:

["course_subject=Robotica", "course_type= C", "course_location= VIV7", "course_teacher= Pozna_C_R", "course_start_hour=14:00 ", "course_end_hour= 15:50"]

As you can see we only need to split each key with '='. You can do this by looping through each value with for loop but there is Array.map method.

let output_array = loc.map(function(value) {
  return value.split('=');
});

And the result is:

[["course_subject", "Robotica"], ["course_type", " C"], ["course_location", " VIV7"], ["course_teacher", " Pozna_C_R"], ["course_start_hour", "14:00 "], ["course_end_hour", " 15:50"]]
Covik
  • 746
  • 6
  • 15
0

You can first decode your url using decodeURI and then array#split on & and then use array#map to arrayp#split each string on =.

let query = "course_subject=Robotica&course_type=%20C&course_location=%20VIV7&course_teacher=%20Pozna_C_R&course_start_hour=14:00%20&course_end_hour=%2015:50";
var result = decodeURI(query).split('&').map(str => str.split('='));
console.log(result);
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51