Function for converting URL hash parameters to an object (key value pairs)

Consider this line: #page?param1=a¶m2=b¶m3=c

The hybrid application that I worked on uses window.location.hashto route the application to the desired page. Often these URLs contain parameters after the hash. Of course, this is not a standard, but it is a good solution that is perfect for our application.

I need to create a function that will take all the parameters in the hash and returns them to the object, for example {param: value}.

I tried solving other issues that include window.location.search, but unfortunately, it just returns an empty string when the parameters are after the hash.

My attempt looks like this:

return JSON.parse('{"' + decodeURI(window.location.hash).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}');

The solution is taken from another question that uses window.location.search, but the use window.location.hashdoes not work correctly, the first parameter (after the question mark) is displayed as undefined.

How to create a function that returns hash parameters in an object?

The desired result for the line above will be as follows:

{ param1: 'a', param2: 'b', param3: 'c' }
+4
source share
3 answers

You can use this function:

function parseParms(str) {
    var pieces = str.split("&"), data = {}, i, parts;
    // process each query pair
    for (i = 0; i < pieces.length; i++) {
        parts = pieces[i].split("=");
        if (parts.length < 2) {
            parts.push("");
        }
        data[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
    }
    return data;
}

This is taken from a .parseParms() larger feature set method on github . I wrote to parse the URL into all its parts.

Input is a string in the form:

"aaa=1&bbb=99&name=Bob"

and it will return the object as follows:

{aaa: 1, bbb: 99, name: "Bob"}

So, if you have other things in the line, besides just the above parameters, you will need to delete them before calling this function.

:

function parseParms(str) {
    var pieces = str.split("&"), data = {}, i, parts;
    // process each query pair
    for (i = 0; i < pieces.length; i++) {
        parts = pieces[i].split("=");
        if (parts.length < 2) {
            parts.push("");
        }
        data[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
    }
    return data;
}

console.log(parseParms("aaa=1&bbb=99&name=Bob"));
Hide result
+12
function parseParms(str) 
{
  var pieces = str.split( "&" ), 
      data = {}, 
      i, parts, key;

  // Process each query pair
  for ( i = 0; i < pieces.length; i++ ) {
    parts = pieces[i].split( "=" );

    // No value, only key
    if ( parts.length < 2 ) {
      parts.push( "" );
    }

    key = decodeURIComponent( parts[ 0 ] );
    value = decodeURIComponent( parts[ 1 ] );

    // Key is an array
    if ( key.indexOf( "[]" ) !== -1 ) {
      key = key.substring( 0, key.indexOf( "[]" ) );

      // Check already there
      if ( "undefined" === typeof data[ key ] ) {
        data[ key ] = [];
      }

      data[ key ].push( value );
    } else {
      data[ key ] = value;
    }
  }
  return data;
}

: https://jsbin.com/xitemecuvi/edit?js,console

, .

0

the method foreEachfor arrays makes it even shorter:

const result = {};
hash.split('&').forEach(item => {
    result[item.split('=')[0]] = decodeURIComponent(item.split('=')[1]);
});
0
source

Source: https://habr.com/ru/post/1539341/


All Articles