1

I've a url similat to example.com/?id[]=15029&id[]=18711&foo=bar#MyTab

I want to get all the id's in the url

var str = window.location.search;
var result = {};
str.replace(/([^?=&]+)(?:[&#]|=([^&#]*))/g, function (match, key, value) {
    result[key] = value || 1;
});
result;

Above code only returns the last id paramenter.

How can I improve it to get all ids in an array?

Mithun Sreedharan
  • 49,883
  • 70
  • 181
  • 236

1 Answers1

0

Got it

function getUrlParam (paramName) {
    var str = window.location.search;
    var result = {};
    str.replace(/([^?=&]+)(?:[&#]|=([^&#]*))/g, function (match, key, value) {
        if (key.indexOf("[]") !== -1) {
            key = key.replace(/\[\]$/, "");
            if(!(result[key])) {
                result[key] = new Array();
            }
            result[key].push(value);
        } else {
            result[key] = value || 1;
        }
    });

    if(result[paramName]){
        return result[paramName];
    } else {
        return '';
    }
};
getUrlParam('id')
Mithun Sreedharan
  • 49,883
  • 70
  • 181
  • 236