0

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?

Junior
  • 11,602
  • 27
  • 106
  • 212
  • 1
    Possible duplicate of [How can I get query string values in JavaScript?](http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – Andreas Jan 25 '16 at 19:12
  • @Andreas thank you for your feedback. but how can I get that code to put all the parameters into an array of objects? It seems to allow me to get one giving parameter at a time – Junior Jan 25 '16 at 19:18
  • 1
    Don't just look for the accepted answer ;) http://stackoverflow.com/a/2880929/402037 – Andreas Jan 25 '16 at 19:24
  • @Andreas thank you. you provided me the help I need to solve it. If you post an answer I will accept it – Junior Jan 25 '16 at 19:38
  • Because I've voted to close this question ("_Possible duplicate of..._") I won't add it as an answer :) – Andreas Jan 25 '16 at 19:43
  • Are you sure that `[ {name: k1, value: v1}, { name: k2, value: v2}, ...]` is what you're after? A straight map of key/value pairs would be more usual. – Alnitak Jan 25 '16 at 19:48
  • I just voted to close it as well. – Junior Jan 25 '16 at 19:49

5 Answers5

3

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;
}
ilian6806
  • 221
  • 1
  • 5
2

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>
Ionut
  • 1,729
  • 4
  • 23
  • 50
0

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"}];
*/
jupadura
  • 71
  • 3
0

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"
...
kagami
  • 592
  • 4
  • 15
0
 var url=new URLSearchParams(window.location.search);
        var params = [];
        for(var value of url.keys())
        {
            params.push({
                name: value,
                value: url.get(value)
            });
        }
Im Im
  • 1
  • 1