1

Let's say I have an address of:

www.example.com/index.php?a=1&b=2&c=3

I want to enter that into an input field like this (value would obviously initially be blank):

<input id="my-input-field" value="www.example.com/index.php?a=1&b=2&c=3">

Then I want JS to parse everything after the ?, take all of the queries ("a", "b", "c") and see if they exist in an array().

Then I want to display a message stating that some of the items in the given URL were missing - but that's the easy part.

The part that I'm having trouble figuring out is: how to break down the URL and only find the first part of each query?


I understand how to strip everything before the question mark (including the question mark):

var str = "www.example.com/index.php?a=1&b=2&c=3";
str = str.substring(str.indexOf("?") + 1);
alert(str);

Fiddle: http://jsfiddle.net/xx3fwhvv/

This returns: a=1&b=2&c=3


The next step could be to split the string up per each &?

var str = "a=1&b=2&c=3";
str = str.split("&");
alert(str);

Fiddle: http://jsfiddle.net/3Lo24byo/

This returns: a=1,b=2,c=3


We can then remove everything after the ='s sign like this:

var str = 'a=1';
str = str.substring(0, str.indexOf('='));
alert(str);

Fiddle: http://jsfiddle.net/vfzvu5mh/

This results in: a

The thing now is how do I loop through the array and do this for each item? That would be the step I need to take.


Then I need to have an array like:

var myArray = array('a','c','d');

In the above array, cross checking the array that we created above to see if any of the values match up should return b as not matching up, as it's not in myArray.

This is where I'm stuck. Any help is appreciated. I'm not very good with JS but I've been working at this trying to figure it out.


All together so far, the code would look something like this:

var str = "www.example.com/index.php?a=1&b=2&c=3";
newStr = str.substring(str.indexOf("?") + 1);
strArray = newStr.split("&");

i = 1;
for {
  newStrArray = strArray[i].substring(0, strArray[i].indexOf('='));
  i++;
}

The above doesn't work for me, but something like that any way.


EDIT (I'll be actively editing this part until the question is answered):

var str = "www.example.com/index.php?a=1&b=2&c=3";
var newStr = str.substring(str.indexOf("?") + 1);
var myStringArray = newStr.split("&");

var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
  myStringArray = myStringArray[i].substring(0, myStringArray[i].indexOf('='));
  alert(myStringArray[i]);
}

Current Fiddle: https://jsfiddle.net/03ho0nbz/

mattroberts33
  • 260
  • 5
  • 19
  • Try [this post](http://stackoverflow.com/a/15866004/456135) – Anupam Jun 01 '16 at 06:12
  • Possible duplicate of [Get querystring array values in Javascript](http://stackoverflow.com/questions/15865747/get-querystring-array-values-in-javascript) – Anupam Jun 01 '16 at 06:14
  • @anu thanks for your comment! I've searched around, my issue isn't how to get the query strings from the URL though, just need to break them up and compare them. – mattroberts33 Jun 01 '16 at 06:14
  • @anu in your second link, I also don't need to get the values for specific query get values, which is what every question on SO seems to be getting at. – mattroberts33 Jun 01 '16 at 06:15
  • Using the function given in my previous comment you can get an array of query params. Use that array to compare – Anupam Jun 01 '16 at 06:17
  • @anu, again, thanks for the comment, I'm interested in all the input there is. I'm actually able to get the array, that's not the problem, it's the comparing part. I don't see anything in the code in those answers that I can use. – mattroberts33 Jun 01 '16 at 06:18

2 Answers2

1

First off, you're overwriting your array with the result of a substring:

myStringArray = myStringArray[i].substring(0, myStringArray[i].indexOf('='));

myStringArray receives the results of the substring, turning it into a string.

To compare myArray with otherArray and see if an element not exists in myArray you can use the indexOf() function:

var myArray = ['a', 'c', 'd'];
var otherArray = ['a', 'b', 'c'];

for(var i=0;i<otherArray.length;i++) { 
    if(myArray.indexOf(otherArray[i]) === -1) {
        console.log('myArray does not have', otherArray[i]); // myArray does not have b
    }
}

Going by your example this would create a loop looking something like:

var str = "www.example.com/index.php?a=1&b=2&c=3";
var newStr = str.substring(str.indexOf("?") + 1);
var myStringArray = newStr.split("&");
var myArray = ['a', 'c', 'd'];

for (var i = 0; i < myStringArray.length; i++) {
  var eqIndex = myStringArray[i].indexOf('=');
  if(eqIndex !== -1) {
      var key = myStringArray[i].substring(0, eqIndex);
      if(myArray.indexOf(key) === -1) {
          alert(key, "not in myArray!");
      }
  }
}

Note that this way of writing JS is fine for learning practices, but if you intend to use JS in a professional setting, please read up on some JS good practices.

What i would do is to fiddle around with JS like you're doing, try and see if you can buy some JS good practices books and also look at how popular frameworks solve things. For professional purpose it's almost always a good idea to use a framework that's well maintained and supported. For example if you would use underscore in this case you could do something like:

var paramKeys = _.chain("a=1&b=2&c=3".split('&')).map(function(params) {
    var p = params.split('=');
    return p[0];
}).value();
_.difference(paramKeys, ['a', 'c', 'd']) // "b"
Elwin Arens
  • 1,542
  • 10
  • 21
  • Hi, Elwin! I'm just working this out still with what you've been providing. I'm still stuck on the first part, I just updated it a little more at the bottom. – mattroberts33 Jun 01 '16 at 06:27
  • Is the double loop what is bad practice? – mattroberts33 Jun 01 '16 at 06:34
  • I've added a working example in the second code block – Elwin Arens Jun 01 '16 at 06:36
  • Yeah, that is amazing. Thank you very much! Could you possibly provide some insight as to what about this is not good practice though? I really appreciate your time. – mattroberts33 Jun 01 '16 at 06:38
  • 1
    What i would do is to fiddle around with JS like you're doing, try and see if you can buy some JS good practices books and also look at how popular frameworks solve things. For professional purpose it's almost always a good idea to use a framework that's well maintained and supported. For example if you'de use underscore in this case you could do: `_.difference(['a','b','c'], ['a', 'c', 'd']) // "b"` – Elwin Arens Jun 01 '16 at 06:43
1

@mattroberts33 I am unable to understand why you are checking first parameter in the url, is there anything deference from www.example.com/index.php?a=1&b=2&c=3 to www.example.com/index.php?b=2&a=1&c=3. I would encourage read parameters based on the keys instead of index. In any url query parameters might jumbled.

Below method will return parameter by passing key and url to the method:

var getParameterByName = function (name, url) {
name = name.replace(/[\[]/, '\\\[').replace(/[\]]/, '\\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
if (url) {
  var results = regex.exec(url);
} else {
  var results = regex.exec(location.search);
}
return results == null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));};

If you still wants to get based on index we can modify above method, But that is not encouraging.

ajay
  • 3,245
  • 4
  • 31
  • 59
  • I don't think it matters to be in any particular order. I'm comparing the query variables provided in the url to those available in a predetermined array, then telling the user which query variables are not available. – mattroberts33 Jun 01 '16 at 07:24