Convert Query string to JSON object using JavaScript

mahabub.devs3
Mahabubur Rahman
Published on Sep, 19 2024 1 min read 0 comments
image

We can do it by some deferent way. Let see the bellow methods 

 

let our current URL : https://devs3.pro/?email=mahabub%40exampla.com&phone=0897788665

 

Method 1: Using URLSearchParams and Object.fromEntries. It work in current all browser.

Object.fromEntries(new URLSearchParams(location.search))

Output:

{email: '[email protected]', phone: '0897788665'}

 

Method 2: Create a simple function as bellow -

function queryStringToObject(queryString) {
  const pairs = queryString.substring(1).split('&');
  // → ["foo=bar", "baz=buzz"]

  var array = pairs.map((el) => {
    const parts = el.split('=');
    return parts;
  });
  // → [["foo", "bar"], ["baz", "buzz"]]

  return Object.fromEntries(array);
  // → { "foo": "bar", "baz": "buzz" }
}

Call the function

queryStringToObject(location.search)

Output : 

{email: 'mahabub%40exampla.com', phone: '0897788665'}

 

 

 

 

0 Comments