Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a url params from array data?

Let's say I can get some data like below:

data = ["s=abc","t=123","a=567","b=789"]

How I can handle these data to obtain a url string like "?s=abc&t=123&a=567&b=789"

I write some code

for(i=0;i<data.length;i++){
  data[i].split("=");
}

but stuck for a while.

Can anyone help me? by the way, the data.length may different each time.

Thanks.

like image 590
Dreams Avatar asked Sep 11 '26 00:09

Dreams


2 Answers

How I can handle these data to obtain a url string like "?s=abc&t=123&a=567&b=789"

Use join with & as glue. This will concat the elements of the array by using & as glue, then you can prepend ? to the resulting string.

var data = ["s=abc", "t=123", "a=567", "b=789"];
var params = '?' + data.join('&');

console.log(params);
document.write(params);

Note: If your parameters contains special characters you can use encodeURIComponent to encode it.

like image 108
Tushar Avatar answered Sep 13 '26 14:09

Tushar


If you need the params to be url encoded, use $.param( data);

http://api.jquery.com/jquery.param/

like image 39
Swaraj Giri Avatar answered Sep 13 '26 13:09

Swaraj Giri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!