Javascript 使用正则表达式从查询字符串中捕获值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10126956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:58:43  来源:igfitidea点击:

Capture value out of query string with regex?

javascriptregexquery-string

提问by Trip

I am trying to select just what comes after name=and before the &in :

我正在尝试选择in之后name=和之前的内容&

"/pages/new?name=J&return_url=/page/new"

So far I have..

到目前为止我有..

^name=(.*?).

I am trying to return in this case, just the J, but its dynamic so it could very several characters, letters, or numbers.

在这种情况下,我试图返回J,但它是动态的,因此它可以有很多字符、字母或数字。

The end case situation would be allowing myself to do a replacestatement on this dynamic variable found by regex.

最终的情况是让我自己对replace正则表达式找到的这个动态变量做一个声明。

回答by vol7ron

/name=([^&]*)/

/name=([^&]*)/

  • remove the ^and end with an &
  • 删除^并以一个结尾&


Example:

例子:

var str     = "/pages/new?name=J&return_url=/page/new";
var matches = str.match(/name=([^&]*)/);
alert(matches[1]);


The better way is to break all the params down (Example using current address):

更好的方法是分解所有参数(使用当前地址的示例):

function getParams (str) {
   var queryString = str || window.location.search || '';
   var keyValPairs = [];
   var params      = {};
   queryString     = queryString.replace(/.*?\?/,"");

   if (queryString.length)
   {
      keyValPairs = queryString.split('&');
      for (pairNum in keyValPairs)
      {
         var key = keyValPairs[pairNum].split('=')[0];
         if (!key.length) continue;
         if (typeof params[key] === 'undefined')
         params[key] = [];
         params[key].push(keyValPairs[pairNum].split('=')[1]);
      }
   }
   return params;
}


var url    = "/pages/new?name=L&return_url=/page/new";
var params = getParams(url);
params['name'];


Update

更新

Though still not supported in any version of IE, URLSearchParamsprovides a native way of retrieving values for other browsers.

尽管仍然不受任何版本的 IE 支持,但URLSearchParams提供了一种为其他浏览器检索值的本机方式。

回答by William Neely

The accepted answer includes the hash part if there is a hash right after the params. As @bishoy has in his function, the correct regex would be

如果参数后面有散列,则接受的答案包括散列部分。正如@bishoy 在他的函数中所拥有的那样,正确的正则表达式是

/name=([^&#]*)/

回答by cruzanmo

Improving on previous answers:

改进以前的答案:

/**
 *
 * @param {string} name
 * @returns {string|null}
 */
function getQueryParam(name) {
  var q = window.location.search.match(new RegExp('[?&]' + name + '=([^&#]*)'));
  return q && q[1];
}

getQueryParam('a'); // returns '1' on page http://domain.com/page.html?a=1&b=2 

回答by Bishoy Hanna

here is the full function (tested and fixed for upper/lower case)

这是完整的功能(针对大写/小写进行了测试和修复)

function getParameterByName (name) 
{
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regexS = "[\?&]" + name.toLowerCase() + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.search.toLowerCase());
    if (results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
}

回答by Karl Barker

The following should work:

以下应该工作:

\?name=(.*?)&

回答by Phil H

var myname = str.match(/\?name=([^&]+)&/)[1];

The [1] is because you apparently want the value of the group (the part of the regex in brackets).

[1] 是因为您显然想要组的值(括号中的正则表达式部分)。

var str = "/pages/new?name=reaojr&return_url=/page/new";
var matchobj = str.match(/\?name=([^&]+)&/)[1];
document.writeln(matchobj); // prints 'reaojr'