如何用哈希解析字符串?

时间:2014-10-16 06:31:28

标签: javascript jquery string

我有一些带有哈希的字符串,之后我需要获得plantype = chine来满足条件。当我把#替换为&它工作正常,但我需要使用#

  var url = href='//somewebsite/index.html?plan=usa#plantype=china';

  var queryString = {};
  url.replace(
    new RegExp("([^?=&]+)(=([^&]*))?", "g"),
    function($0, $1, $2, $3) { 
      queryString[$1] = $3; 
    }
  );

  if (queryString['plantype'] == 'china') {
   // the condition is not satisfied when i use # in a string
  }

如何修复它,以及我做错了什么?

2 个答案:

答案 0 :(得分:1)

尝试

var queryString = {}
, url = 'href=//somewebsite/index.html?plan=usa#plantype=china'
, url = url.split("#")[1].split("=");
queryString[url[0]] = url[1];
if (queryString["plantype"] === "china") {
  console.log(queryString)
}



var queryString = {}
, url = 'href=//somewebsite/index.html?plan=usa#plantype=china'
, url = url.split("#")[1].split("=");
queryString[url[0]] = url[1];
if (queryString["plantype"] === "china") {
  console.log(queryString)
}




答案 1 :(得分:0)

您必须在正则表达式中检查#,将&替换为#

new RegExp("([^?=#]+)(=([^#]*))?", "g"),