7

PHP's http_build_query function Generates URL-encoded query string I need the exact same functionality in javascript.

Function example:

$data = array(
    'foo' => 'bar',
    'baz' => 'boom',
    'cow' => 'milk',
    'php' => 'hypertext processor'
);

echo http_build_query($data) . "n";

Output:

foo=bar&baz=boom&cow=milk&php=hypertext+processor

I want the same output in javascript. I tried encodeURIComponent but it's solving adifferent purpose.

0

1 Answer 1

21

There's URLSearchParams:

const params = new URLSearchParams({
  foo: 'bar',
  baz: 'boom',
  cow: 'milk',
  php: 'hypertext processor'
});
const str = params.toString();
console.log(str);

For obsolete browsers which don't support it, you can use this polyfill.

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

8 Comments

But beware - it's use not in all browsers
Yeah... all but IE, Blackberry, QQ (wtf is that ?) and Baidu Brower. I think we can say everywhere.
Not all of us are lucky enough to be able to drop IE support yet...
@AjayP Not in IE - the latest release of IE was IE11, from 2013
Caution: http_build_query and URLSearchParams behave differently with nested arrays.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.