This example originated from an ActionScript project.  The project required me to extract values from an URL/querystring.  A bit tedious in ActionScript 3.0 where I always prefer to use XML for speed.  But anyway may be a slicker solution out there but this is what I came up with.

function getValueFromTxt(valueName){
	var rawString = window.location.href + "&";
	var startQs = rawString.search(valueName);
	var endQs = rawString.length + 1;
	rawString = rawString.substring(startQs, endQs);
	var startPosPName = rawString.search(valueName)+1;
	var equalPosPName = rawString.indexOf("=",startPosPName)+1;
	var endPosPName = rawString.indexOf("&",equalPosPName);
	return rawString.substring(equalPosPName, endPosPName);
}

If you took the following URL with its name/value pairs.

http://www.mustbebuilt.co.uk/demo/valueFromQueryString.html?size=10&weight=400&colour=Green&snake=oil

To extract the individual values for named size, weight, colour and snake by calling the getValueFromTxt() function passing the name of the name/value pair.  ie

var weight = getValueFromTxt("weight");

Note: For my string manipulations to work I added an extra ampersand to the end of the querystring.

See a working demo here

Leave a Comment