JS从url hash获取param

时间:2013-07-31 12:14:05

标签: javascript anchor

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

在fucn _GET中我需要检查param是否存在,如果存在则返回它。

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,如果我控制台.log(_GET(“设备”))或人,则为null

3 个答案:

答案 0 :(得分: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)
  });
})();

答案 1 :(得分: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;
}

答案 2 :(得分:0)

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

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