开发者

How do I get the value of a URL paramater in javascript?

I have a set of URLs from which I want to extract the value of a certain parameter.

For example:

http://example.com/#!/dp/dp.php?g=4346&h=fd34&kl=45fgh&bl=nmkh
http://example.com/#!/dp/dp.php?h=fd34&g=4346&kl=45fgh&bl=nmkh
http://example.com/#!/dp/dp.php?h=fd34&kl=45fgh&g=4346&bl=n开发者_运维百科mkh
http://example.com/#!/dp/dp.php?h=fd34&kl=45fgh&bl=nmkh&g=4346

I want use javascript (regex) to get the value of the parameter g.

Can someone help me with this?


var gMatches = url.match(/[?&]g=[^&]*/);
var g = gMatches[1];

broken down:

[?&]         # starts with a ? or &
g=           # contains g and an equals
[^&]*        # contains any character (except &) 0+ times

very primitive but should work.


var url = window.location.href;
getParameter("g=", url, "&");

function getParameter(parameter, buffer, delimiter)
{
   var start = buffer.indexOf(parameter);
   if (start == -1)
      return null;
   var data = buffer.slice(start);
   if(data.match(delimiter) != null)
      var end = data.indexOf(delimiter);
   else
      var end = data.length;
   data = data.slice(0, end);
   var eq = data.indexOf("=");
   data = data.slice(eq+1);
   return data;
}


var results = new Array;
results = url.match(/[\?\&]g=([^&]*)/);

This should contain only the first value of g, not the entire "g=blah" string.


try this:

var url = window.location.href;
var name = 'g';
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var results = new RegExp("[\\?&]" + name + "=([^&#]*)").exec(url);
if (results != null)
{
    var g_url_value = results[1];
}


var str = 'http://domain.com/#!/dp/dp.php?g=4346&h=fd34&kl=45fgh&bl=nmkh';
var reg = /(\&|\?)g=([^&]+)&?/;
console.log(str.match(reg)[2]);


Use this function.

function getParameterByName(name) {

    var match = RegExp('[?&]' + name + '=([^&]*)')
                    .exec(window.location.search);

    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));

}

Call it like

var url = "http://domain.com/#!/dp/dp.php?g=4346&h=fd34&kl=45fgh&bl=nmkh";
var parm =  getParameterByName("g");

Disclaimer: Shameless port of James Padolsey code from http://james.padolsey.com/javascript/bujs-1-getparameterbyname/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜