简体   繁体   中英

How to Get Hash Parameters from URL

console.log(_GET("appid"));

in fucn _GET I need check if param exist and return it if exist.

function _GET(paramName) {
    var hash = window.location.hash; // #appid=1&device&people=

    //this needs to be not static
    if (/appid=+\w/.test(window.location.hash)) {
        //and somehow parse it and return;
    }
    return false;
}

I expect to see 1 in console and if I console.log(_GET("device")) or people then null

function _GET(paramName) {
    var hash = window.location.hash.match(new RegExp("appid=+\w", 'gi')); // #appid=1&device&people=

    //this needs to be not static
    if (hash) { 
        //and somehow parse it and return;
    }
    return false;
}

You need to use String.match and pass in a RegExp object instead:

function _GET(paramName) {
    var pattern = paramName + "=+\w";
    return (window.location.hash.match(new RegExp(pattern, 'gi'))) != null;
}
import params from './url-hash-params.mjs';

// example.com/#city=Foo&country=Bar
const { city, country } = parms;

url-hash-params.mjs

export default (function() {
  const params = new Map();

  window.addEventListener('hashchange', updateParams);
  updateParams();

  function updateParams(e) {
    params.clear();
    const arry = window.location.hash.substr(1).split('&').forEach(param => {
      const [key, val] = param.split('=').map(s => s.trim());
      params.set(key, val);
    });
  }

  return new Proxy(params, {
    get: (o, key) => o.get(key)
  });
})();

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