Jquery/Javacript: How do i get parameters from the url if there are multiple instances of it

Hi Experts,

I have the below function which works great but it only gets one of the variables if there are multiples... see examples:

http://www.example.com/?type=blue - works fine
http://www.example.com/?type=red&type=blue - gets the first one

Is there anyway to create an array of them if there are multiple instances? many thanks for your help!

function urlParam(name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (results === null) {
        return null;
    } else {
        return results[1] || 0;
    }
}

Open in new window

maccaj51Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Tom BeckCommented:
Function to search for a given parameter (name) and return an array of all values for parameters with that name. Returns null if the parameter does not exist.
function urlParam(name) {
	// EXAMPLE: search = '?type=red&type=green&type=blue&val=xxx'
	var hrefSearch = window.location.search;
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(hrefSearch);
    if (results === null) {
        return null;
    } else {
		hrefSearch = hrefSearch.substr(1);
		hrefSearch = hrefSearch.split('&');
		   var matching = [];
		   for (var i=0; i<hrefSearch.length; i++) {
			   var val = hrefSearch[i].split('=');
			   if (val[0] === name) { matching.push(val[1]) }
		   }
           return matching;
    }
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
maccaj51Author Commented:
You're a hero Tom - many thanks
0
Tom BeckCommented:
You're welcome. Thanks for the points.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
jQuery

From novice to tech pro — start learning today.