如何从URL获取哈希参数

问题描述 投票:1回答:3
console.log(_GET("appid"));

在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;
}

我希望在控制台中看到1,如果我console.log(_GET(“ device”))或其他人,则为null

javascript anchor
3个回答
0
投票

您需要使用String.match并传入RegExp对象:

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

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

0
投票
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;
}
© www.soinside.com 2019 - 2024. All rights reserved.