3

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.

6 Answers 6

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

1

You can just use join function. it converts arrays into strings then add the & as a delimiter then concatenate "?";

var new_data = '?'+data.join('&');

Comments

1

Loop through your data array and concatenate ampersand '&' with each element and remove last '&' using slice.

data = ["s=abc","t=123","a=567","b=789"];
    link="?";
    for(i=0;i<data.length;i++){
      link+=data[i]+"&";
    }
    link=link.slice(0,-1);
    console.log(link);

1 Comment

Please add some explanation to your answer
0

If you want to encode the value - if the values not already encoded

data = ["s=abc", "t=123", "a=567", "b=7 89"]
var params = data.map(function(item) {
  return item.replace(/=(.*)/, function(m, value) {
    return '=' + encodeURIComponent(value)
  })
}).join('&');
snippet.log(params)
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Comments

0

I would use a hash for the key/value pairs and leverage jQuery to serialize the params into a string you can use.

var serializedParams = {
  s: 'abc',
  t: '123',
  a: '567',
  b: '789'
};

$.param(serializedParams);

// Returns:
// s=abc&t=123&a=567&b=789

or you can just manually construct the string yourself.

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

data.join('&');

// Returns:
// s=abc&t=123&a=567&b=789

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.