Given that you're limited to using JavaScript, what angelwatt said is right on
the proverbial money, and the solution presented by mrogers is a very good
basic answer.
I couldn't resist the urge to tinker, though, and came up with a little variant.
If you split around both the '&' and the '=', you get a ready-made array.
Now your search doesn't have to bother with substrings; it's a simple string
compare on every even array element; when you match, the odd one's your
answer.
Then, just to cover all bases, I allowed that there might be more than one
"name=value" pair, with a different value for the same name.
Also, I didn't like the idea of processing the Query-String every time I needed
to extract a value, so I kept the result array around.
Here's what I came up with:
// Return an array:
// item [J*2] is the Jth variable name
// item [(J*2)+1] is the Jth variable value
// Zero-length array if no Query-String Parameters
// Do it in a single step.
function getVarVals(){
var queryParams = window.location.search.substring(1);
var resltArray = new Array;
var qpSplit = new RegExp('[&=]');
resltArray = queryParams.split(qpSplit);
return resltArray;
}
// Globalize the array of Query-String Parameters
// Globalize the index last examined.
var GlobalQueryString = getVarVals();
var gqsIndx = 0;
// Retrieve the value associated with the named QS parameter.
// To allow for more than one instance occuring in the QS line,
// set the Global Query String Index to just after the last
// one retrieved, i.e., the first one to start the next search.
// Let the caller manage tracking it; the second parameter to
// this function is the index number at which to start the search.
// If not found, return null and reset gqsIndx to zero.
function getQSval(parmNam, initlIndx) {
var foundIndx = 0;
var reslt = null;
var indx = ((initlIndx+1)&(-2)) ; // Normalize to next even no.
for ( indx = indx ; indx < GlobalQueryString.length ; indx +=2 ) {
if ( parmNam == GlobalQueryString[indx] ) {
reslt = GlobalQueryString[indx+1];
foundIndx = indx+1;
break;
}
}
gqsIndx = foundIndx;
return reslt;
}
// A simple-minded test.
// Show all instances of a given named QS variable
function showQSvals(parmNam) {
document.write('Values for '+parmNam+'<br>');
while ( valVal = getQSval(parmNam, gqsIndx) ) {
document.write(valVal +'<br>');
}
}
In my test-case I had
?TVal=TestValue&SVal=SecondValue&TVal=Twicet&SVal=Thricet
(as well as another test case with no QS Params).
Anyway, I thought I'd make my small contribution of this tweak to this forum.
Keep up the good work!