Parsing an URL in JavaScript

感情迁移 提交于 2019-12-02 07:13:12

问题


I need to parse url in JavaScript.

Here is my code:

var myRe = /\?*([^=]*)=([^&]*)/;
var myArray = myRe.exec("?page=3&Name=Alex");


for(var i=1;i<myArray.length;i++)
{
    alert(myArray[i]);   
}

Unfortunately it only works for first name=value pair.

How I can correct my code?


回答1:


exec returns a match, or null if no match found. So you need to keep execing until it returns null.

var myRe = /\?*([^=]*)=([^&]*)/;
var myArray;
while((myArray = myRe.exec("?page=3&Name=Alex")) !== null)
{
  for(var i=1;i<myArray.length;i++)
  {
      alert(myArray[i]);   
  }
}

Also, you're regex is wrong, it definately needs th g switch, but I got it working using this regex:

var regex = /([^=&?]+)=([^&]+)/g;

See Live example: http://jsfiddle.net/GyXHA/




回答2:


If all you're trying to do is get query string name/value pairs you could do something like this:

function getQueryStringValue(varName) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");

    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == varName) { return pair[1]; }
    }
}



回答3:


var qs="da?page=3&page=4&Name=&xxx=43&page=&#adasdsadsa";
var params=qs.replace(/^.*\??/g,'').replace(/#.*/g,'').match(/[^&\?]+/g);
var args={};
if(params)for(var i=0;i<params.length;i++) {
  var propval=params[i].split('=');
  if(!args.hasOwnProperty(propval[0]))args[propval[0]]=[];
  args[propval[0]].push(propval[1]);
}

// result:
// args=== {
//   Name: [""],
//   page: ["3","4",""],
//   xxx: ["43"]
// }


来源:https://stackoverflow.com/questions/7283941/parsing-an-url-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!