Junior
Junior

Reputation: 11990

How can I put all the URL parameters in array of objects using jQuery?

I have a giving string/url like this https://example.com/loadcontent?var1=100&var2=:somevar&var3=:morevariables

I need to loop thought each parameter in the url. If the value starts with : this indicated that it is a variable an I will need to change that value dynamically by looking at the corresponding meta attribute that matches that variable.

Here is my code in which loops over an array and sets the value of the parameters.

    var baseURL = getBaseURL(url);

    var params = getParams(url);
    var newParams = $.each(params, function(index, param){

       if( param.value.substring(0, 1) == ':'){
           var myVar = param.value.substring(1);
           param.value = $('meta[name=" + myVar + "']).attr('value');
       }

    });

    var finalURL = baseURL + '?' + jQuery.param( newParams );

function getParams(url){
  // This function should return an array of objects. Each object should have 2 properties "value" and "name". The "name" property should be the name of the parameter (ie. var1, var2, var3 .....) and the "value" attribute should contains the value of the parameter (ie. 100, :somevar, :morevariables)


}

function getBaseURL(url){

  var cutoff = url.indexOf('?');

  if( cutoff > -1){
     return url.substring(0, cutoff - 1);
  }

  return url;

}

I need help converting the parameters of a giving URL to array of object. How can I do this in jQuery?

Upvotes: 0

Views: 4172

Answers (5)

Im Im
Im Im

Reputation: 1

 var url=new URLSearchParams(window.location.search);
        var params = [];
        for(var value of url.keys())
        {
            params.push({
                name: value,
                value: url.get(value)
            });
        }

Upvotes: 0

kagami
kagami

Reputation: 611

You don't even need JQuery for this.

<script type="text/javascript">
var paramStr = window.location.search;
var params = paramStr.substring(1, paramStr.length).split('&');
var paramList = [];
for (var index=0; index < params.length; index++) {
    var param = params[index].split('=');
    paramList.push({name: param[0], value: param[1]});
}
</script>

The result:

[Object]0: Object
name: "a"
value: "b"
...

Upvotes: 0

jupadura
jupadura

Reputation: 71

With a regular expresion and JSON.parse:

 var url = 'https://example.com/loadcontent?var1=100&var2=:somevar&var3=:morevariables';

url = url.replace(/^.*\?/,'');
url = url.replace(/(\w+)=?([\w:]*)/g,'{"name":"$1","value":"$2"}');
url = url.replace(/&/g,',');

var paramsObject = JSON.parse("["+url+"]");


/*
Returns: 

Array [{"name":"var1","value":"100"},{"name":"var2","value":":somevar"},{"name":"var3","value":":morevariables"}];
*/

Upvotes: 0

Ionut
Ionut

Reputation: 1749

Here is an example using map

var url = 'https://example.com/loadcontent?var1=100&var2=:somevar&var3=:morevariables&test';

function getParamArray(url) {
  var queryString = url.substring(url.lastIndexOf("?") + 1);

  return queryString.split('&').map(function(sParam) {
    var param = sParam.split('=');

    return {
      name: param[0],
      value: decodeURIComponent(param[1])
    };
  });
}

document.getElementById("output").innerHTML = JSON.stringify(getParamArray(url), null, 2);
<pre id="output"></pre>

Upvotes: 2

ilian6806
ilian6806

Reputation: 221

You dont need jQuery for this one.

function getParams(url) {

        var queryString = url.substring(url.indexOf('?') + 1);
        var paramsArr = queryString.split('&');
        var params = [];

        for (var i = 0, len = paramsArr.length; i < len; i++) {
            var keyValuePair = paramsArr[i].split('=');
            params.push({
                name: keyValuePair[0],
                value: keyValuePair[1]
            });
        }

        return params;
}

Upvotes: 3

Related Questions