6

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.

Ajay P.
  • 455
  • 1
  • 6
  • 14

1 Answers1

19

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.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320