3

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 Poriya
  • 353
  • 1
  • 4
  • 14

1 Answers1

11

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
  • 313,535
  • 40
  • 245
  • 254