javascriptnode.jstypescripturlurl-routing

Hot to get search parameters as an object from a url containing hash?


So I have a url with this format:

https://my-app.com/my-route/someOtherRoute#register?param1="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 = `https://my-app.com/my-route/someOtherRoute#register?param1="122"&param2="333"`
const parsedUrl = urlTool.parse(url, true)
const { pathName, hash } = parsedUrl

So up to now, my hash have this value #register?param1="122"&param2="333" but how can I get the query strings in a dynamic way? 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?


Solution

  • Using SearchParams

    var url = `https://my-app.com/my-route/someOtherRoute#register?param1="122"&param2="333"`;
    console.log(new URL(`https://1.com?${url.split("?")[1]}`).searchParams.get("param1"));

    Building an object using String#split and Array#reduce

    var url = `https://my-app.com/my-route/someOtherRoute#register?param1="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;
      }, {});
    }
    
    console.log(getParamsAfterHash(`https://my-app.com/my-route/someOtherRoute#register?param1="122"&param2="333"`));