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/