Mongo
Mongo

Reputation: 151

how to parse string with hash?

I have some string with the hash, after which I need get plantype=chine to satisfied the condition. when I replace the # to & it works fine, but I need to use #

  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
  }

How to fix it, and what I'm doing wrong?

Upvotes: 0

Views: 70

Answers (2)

Barry
Barry

Reputation: 3733

You must check for # in the regular expression, replace & by #

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

Upvotes: 0

guest271314
guest271314

Reputation: 1

Try

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

Upvotes: 1

Related Questions