简体   繁体   English

如何从 URL 获取哈希参数

[英]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.在 fucn _GET 我需要检查参数是否存在并在存在时返回它。

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我希望在控制台中看到 1,如果我 console.log(_GET("device")) 或 people 然后为空

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:您需要使用String.match并传入RegExp对象:

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 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)
  });
})();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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