Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any function in javascript like PHP's http_build_query function? [duplicate]

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.

like image 240
Ajay Poriya Avatar asked Jul 13 '26 00:07

Ajay Poriya


1 Answers

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.

like image 127
CertainPerformance Avatar answered Jul 14 '26 13:07

CertainPerformance



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!