Get query strings as an object after a url with hash


So I have a url with this format . :"122"&param2="333"

I know how to get the query strings for a normal url but I was not able to get query strings which come after #

I using node-url and I did this so far :

import * as urlTool from 'url';
const url = ""122"&param2="333"
const parsedUrl = urlTool.parse(url,true);
const { pathName, hash } = parsedUrl

So upto now, my hash have this value #register?param1="122"&param2="333" but how can I get the query strings in a dynamic way, because the query strings may, or may not be there all the time, and I don’t know the name of them as well, how can I get any query strings which may be come after the # in a url?


Using SearchParams

var url = `"122"&param2="333"`;
console.log(new URL(`${url.split("?")[1]}`).searchParams.get("param1"));

Building an object using String#split and Array#reduce

var url = `"122"&param2="333"`;
console.log(url.split("?")[1].split("&").reduce(function(result, param) {
  var [key, value] = param.split("=");
  result[key] = value;
  return result;
}, {}));

Thought it would be safer to write something like this:

function getParamsAfterHash(url) {
  if (typeof url !== "string" || !url) url = location.href;
  url = url.split("#")[1];
  if (!url) return {};
  url = url.split("?")[1];
  if (!url) return {};
  return url.split("&").reduce(function(result, param) {
    var [key, value] = param.split("=");
    result[key] = value;
    return result;
  }, {});


Answered By – nick zoum

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published