简体   繁体   中英

Get multiple values from hash in URL

www.domain.com/lookbook.html#look0&product1

On page load I would like to grab the whole hash ie. #look0&product1 then split it up and save the number of the look ie 0 in a variable called var look and the number of the product ie 1 in another variable called var product . Not sure how to achieve this.

Is this also the best way of passing and retrieving such parameters? Thanks

Use var myHash = location.hash to get hash part of URL. Than do var params = myHash.split('&') and after that for each part do part.split('=') to get key-value pairs.


Maybe it's better to pass these parameters via GET from PHP side and than post them inside page when page is processed via PHP?

<input type="hidden" name="look" value="<?php echo isset($_GET['look']) ? $_GET['look'] : '';?>"/>

Here's the pure Javascript method:

function parseHash(hash) {
  // Remove the first character (i.e. the prepended "#").
  hash = hash.substring(1, hash.length);

  // This is where we will store our properties and values.
  var hashObj = {};

  // Split on the delimiter "&" and for each key/val pair...
  hash.split('&').forEach(function(q) {
    // Get the property by splitting on all numbers and taking the first entry.
    var prop = q.split(/\d/)[0];
    // Get the numerical value by splitting on all non-numbers and taking the last entry.
    var val_raw = q.split(/[^\d]/);
    var val = val_raw[val_raw.length - 1]

    // If the property and key are defined, add the key/val pair to our final object.
    if (typeof prop !== 'undefined' && typeof val !== 'undefined') {
      hashObj[prop] = +val;
    }
  });

  return hashObj;
}

Use like:

parseHash(window.location.hash /* #book10&id1483 */)
/* returns: Object {book: 10, id: 1483} */

I suggest using the norm for passing values through the location's hash: prop=value . Ex: #book=10&id=311 . Then you can easily split on = for each property.

You can use .match(re) method with use of regular expression to extract the number from the given string.

You can try this:

var hashes = location.hash.split('&'); // get the hash and split it to make array
var values = hashes.map(function(hash){ // use .map to iterate and get a new array
    return hash.match(/\d+/)[0]; // returns the numbers from the string.
});

 var loc = "look0345345345&product1"; var hashes = loc.split('&'); var values = hashes.map(function(hash){ return hash.match(/\\d+/)[0]; }); document.body.innerHTML = '<pre>'+ JSON.stringify(values) + '</pre>'; 

You could try this:

 var url = 'www.domain.com/lookbook.html#look0&product1' , result = {} , expr = RegExp(/[#&]([a-zA-z]+)(\\d+)/g); var parts = expr.exec(url); while(parts != null && parts.length == 3) { result[parts[1]] = parts[2]; parts = expr.exec(url); } var look = result['look'] , product = result['product']; document.getElementById('result').innerHTML = 'look = ' + look + '<br>' + 'product = ' + product; 
 <p id='result'></p> 

We are basically using a regular expression to divide the parameter name and value into two groups that we can then get by calling expr.exec(url) .

Each time we call expr.exec(url) , we get the next set of name and value groups.

We set the value of the parameter to its name in the result object .

In the regular expression /[#&]([a-zA-z]+)(\\d+)/g , the g after the /.../ means match each time find the two groups.

The two groups are prefaced by either & or # ( [#&] ). The first group is a String of letters ([a-zA-z]+) , the name of the parameter. The second is a String of numbers (\\d+) , the value you are looking for.

The regex returns the String that matches the pattern as the first result in the parts array, followed by the groups matched, which which means that our two groups in each iteration will be parts[1] and parts[2] .

you should use:

 function parseHash(hash){ hash = hash.substring(1, hash.length); //remove first character (#) var obj ={}; //create the output var qa = hash.split('&'); //split all parameters in an array for(var i = 0; i < qa.length; i++){ var fra1 = qa[i].split('='); //split every parameter into [parameter, value] var prop = fra1[0]; var value = fra1[1]; if(/[0-9]/.test(value) && !isNaN(value)){ //check if is a number value = parseInt(value); } obj[prop] = value; //add the parameter to the value } return obj; } document.querySelector("input.hash").onkeyup = function(){ console.log( parseHash(document.querySelector("input.hash").value)); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" class="hash"/> <p class="output"></p> 

use as

parseHash(location.hash /* #look=0&product=1 );

/ returns {look: 0, product: 1} /

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM