如何将JavaScript与PHP的preg_match_all()类似的正则表达式与正则表达式匹配?

时间:2022-06-26 11:45:24

I am trying to parse url-encoded strings that are made up of key=value pairs separated by either & or &.

我正在尝试解析由key=值对组成的url编码的字符串。

The following will only match the first occurrence, breaking apart the keys and values into separate result elements:

以下将只匹配第一次出现,将键和值拆分为单独的结果元素:

var result = mystring.match(/(?:&|&)?([^=]+)=([^&]+)/)

The results for the string '1111342=Adam%20Franco&348572=Bob%20Jones' would be:

字符串'1111342=Adam%20Franco&348572=Bob%20Jones'的结果如下:

['1111342', 'Adam%20Franco']

Using the global flag, 'g', will match all occurrences, but only return the fully matched sub-strings, not the separated keys and values:

使用全局标记'g'将匹配所有的事件,但只返回完全匹配的子字符串,而不是分离的键和值:

var result = mystring.match(/(?:&|&)?([^=]+)=([^&]+)/g)

The results for the string '1111342=Adam%20Franco&348572=Bob%20Jones' would be:

字符串'1111342=Adam%20Franco&348572=Bob%20Jones'的结果如下:

['1111342=Adam%20Franco', '&348572=Bob%20Jones']

While I could split the string on & and break apart each key/value pair individually, is there any way using JavaScript's regular expression support to match multiple occurrences of the pattern /(?:&|&)?([^=]+)=([^&]+)/ similar to PHP's preg_match_all() function?

虽然我可以把字符串&单独分开每一个键/值对,有什么方法使用JavaScript来匹配的正则表达式支持多个模式的出现/(?:& |和)?([^ =]+)=([^ &]+)/类似于PHP的preg_match_all()函数?

I'm aiming for some way to get results with the sub-matches separated like:

我的目标是获得与分相匹配的结果:

[['1111342', '348572'], ['Adam%20Franco', 'Bob%20Jones']]

or

[['1111342', 'Adam%20Franco'], ['348572', 'Bob%20Jones']]

13 个解决方案

#1


152  

I would suggest an alternative regex, using sub-groups to capture name and value of the parameters individually:

我建议使用另一个regex,使用子组分别捕获参数的名称和值:

function getUrlParams(url) {
  var re = /(?:\?|&(?:amp;)?)([^=&#]+)(?:=?([^&#]*))/g,
      match, params = {},
      decode = function (s) {return decodeURIComponent(s.replace(/\+/g, " "));};

  if (typeof url == "undefined") url = document.location.href;

  while (match = re.exec(url)) {
    params[decode(match[1])] = decode(match[2]);
  }
  return params;
}

var result = getUrlParams("http://maps.google.de/maps?f=q&source=s_q&hl=de&geocode=&q=Frankfurt+am+Main&sll=50.106047,8.679886&sspn=0.370369,0.833588&ie=UTF8&ll=50.116616,8.680573&spn=0.35972,0.833588&z=11&iwloc=addr");

result is an object:

结果是一个对象:

{
  f: "q"
  geocode: ""
  hl: "de"
  ie: "UTF8"
  iwloc: "addr"
  ll: "50.116616,8.680573"
  q: "Frankfurt am Main"
  sll: "50.106047,8.679886"
  source: "s_q"
  spn: "0.35972,0.833588"
  sspn: "0.370369,0.833588"
  z: "11"
}

The regex breaks down as follows:

regex分解如下:

(?:            # non-capturing group
  \?|&         #   "?" or "&"
  (?:amp;)?    #   (allow "&", for wrongly HTML-encoded URLs)
)              # end non-capturing group
(              # group 1
  [^=&#]+      #   any character except "=", "&" or "#"; at least once
)              # end group 1 - this will be the parameter's name
(?:            # non-capturing group
  =?           #   an "=", optional
  (            #   group 2
    [^&#]*     #     any character except "&" or "#"; any number of times
  )            #   end group 2 - this will be the parameter's value
)              # end non-capturing group

#2


64  

You need to use the 'g' switch for a global search

您需要使用“g”开关进行全局搜索。

var result = mystring.match(/(&|&)?([^=]+)=([^&]+)/g)

#3


34  

If you don't want to rely on the "blind matching" that comes with running exec style matching, JavaScript does come with match-all functionality built in, but it's part of the replace function call, when using a "what to do with the capture groups" handling function:

如果您不想依赖于运行exec风格匹配的“盲匹配”,那么JavaScript将附带所有内置的功能,但它是替换函数调用的一部分,当使用“如何处理捕获组”的处理函数时:

var data = {};

var getKeyValue = function(fullPattern, group1, group2, group3) {
  data[group2] = group3;
};

mystring.replace(/(?:&|&)?([^=]+)=([^&]+)/g, getKeyValue);

done.

完成了。

Instead of using the capture group handling function to actually return replacement strings (for replace handling, the first arg, called a here, is the full pattern match, and subsequent args are individual capture groups, in this case b being group 1, c group 2, etc) we simply take the groups 2 and 3 captures, and cache that pair.

而不是使用捕获组处理函数来返回替换字符串(更换处理,第一个参数,称为,是完整的模式匹配,和随后的arg游戏个人捕捉组,在这种情况下,b组1,c组2,等等)我们只是组2和3了,一对和缓存。

So, rather than writing complicated parsing functions, remember that the "matchAll" function in JavaScript is simply "replace" with a replacement handler function, and much pattern matching efficiency can be had.

因此,与其编写复杂的解析函数,还不如记住JavaScript中的“matchAll”函数仅仅是“替换”替换处理函数,并且可以有许多模式匹配效率。

#4


20  

For capturing groups, I'm used to using preg_match_all in PHP and I've tried to replicate it's functionality here:

对于捕获组,我习惯使用PHP中的preg_match_all,我尝试在这里复制它的功能:

<script>

// Return all pattern matches with captured groups
RegExp.prototype.execAll = function(string) {
    var match = null;
    var matches = new Array();
    while (match = this.exec(string)) {
        var matchArray = [];
        for (i in match) {
            if (parseInt(i) == i) {
                matchArray.push(match[i]);
            }
        }
        matches.push(matchArray);
    }
    return matches;
}

// Example
var someTxt = 'abc123 def456 ghi890';
var results = /[a-z]+(\d+)/g.execAll(someTxt);

// Output
[["abc123", "123"],
 ["def456", "456"],
 ["ghi890", "890"]]

</script>

#5


14  

Set the g modifier for a global match:

为全局匹配设置g修饰符:

/…/g

#6


10  

Source: https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec

来源:https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec

Finding successive matches

If your regular expression uses the "g" flag, you can use the exec() method multiple times to find successive matches in the same string. When you do so, the search starts at the substring of str specified by the regular expression's lastIndex property (test() will also advance the lastIndex property). For example, assume you have this script:

如果正则表达式使用“g”标志,则可以多次使用exec()方法来查找相同字符串中的连续匹配。当您这样做时,搜索从正则表达式的lastIndex属性指定的子字符串开始(test()也将推进lastIndex属性)。例如,假设您有这个脚本:

var myRe = /ab*/g;
var str = 'abbcdefabh';
var myArray;
while ((myArray = myRe.exec(str)) !== null) {
  var msg = 'Found ' + myArray[0] + '. ';
  msg += 'Next match starts at ' + myRe.lastIndex;
  console.log(msg);
}

This script displays the following text:

此脚本显示以下文本:

Found abb. Next match starts at 3
Found ab. Next match starts at 912

Note: Do not place the regular expression literal (or RegExp constructor) within the while condition or it will create an infinite loop if there is a match due to the lastIndex property being reset upon each iteration. Also be sure that the global flag is set or a loop will occur here also.

注意:不要将正则表达式(或RegExp构造函数)放在while条件中,否则将创建一个无限循环,如果有匹配,则将在每次迭代中重置lastIndex属性。同时,也要确保在这里设置了全局标志或循环。

#7


2  

If someone (like me) needs Tomalak's method with array support (ie. multiple select), here it is:

如果有人(像我一样)需要使用数组支持的Tomalak方法。多重选择),这里是:

function getUrlParams(url) {
  var re = /(?:\?|&(?:amp;)?)([^=&#]+)(?:=?([^&#]*))/g,
      match, params = {},
      decode = function (s) {return decodeURIComponent(s.replace(/\+/g, " "));};

  if (typeof url == "undefined") url = document.location.href;

  while (match = re.exec(url)) {
    if( params[decode(match[1])] ) {
        if( typeof params[decode(match[1])] != 'object' ) {
            params[decode(match[1])] = new Array( params[decode(match[1])], decode(match[2]) );
        } else {
            params[decode(match[1])].push(decode(match[2]));
        }
    }
    else
        params[decode(match[1])] = decode(match[2]);
  }
  return params;
}
var urlParams = getUrlParams(location.search);

input ?my=1&my=2&my=things

输入吗?我可做可做= 1 = 2 =

result 1,2,things (earlier returned only: things)

结果1、2、事物(以前只返回:东西)

#8


2  

Just to stick with the proposed question as indicated by the title, you can actually iterate over each match in a string using String.prototype.replace(). For example the following does just that to get an array of all words based on a regular expression:

为了坚持标题所示的建议问题,您实际上可以使用string .prototype.replace()在字符串中迭代每个匹配。例如,下面这样做只是为了得到基于正则表达式的所有单词的数组:

function getWords(str) {
  var arr = [];
  str.replace(/\w+/g, function(m) {
    arr.push(m);
  });
  return arr;
}

var words = getWords("Where in the world is Carmen Sandiego?");
// > ["Where", "in", "the", "world", "is", "Carmen", "Sandiego"]

If I wanted to get capture groups or even the index of each match I could do that too. The following shows how each match is returned with the entire match, the 1st capture group and the index:

如果我想要得到每个匹配的集合或者索引,我也可以这样做。以下显示了每个匹配如何与整个匹配返回,第一个捕获组和索引:

function getWords(str) {
  var arr = [];
  str.replace(/\w+(?=(.*))/g, function(m, remaining, index) {
    arr.push({ match: m, remainder: remaining, index: index });
  });
  return arr;
}

var words = getWords("Where in the world is Carmen Sandiego?");

After running the above, words will be as follows:

在运行上述内容后,将会有以下几个字:

[
  {
    "match": "Where",
    "remainder": " in the world is Carmen Sandiego?",
    "index": 0
  },
  {
    "match": "in",
    "remainder": " the world is Carmen Sandiego?",
    "index": 6
  },
  {
    "match": "the",
    "remainder": " world is Carmen Sandiego?",
    "index": 9
  },
  {
    "match": "world",
    "remainder": " is Carmen Sandiego?",
    "index": 13
  },
  {
    "match": "is",
    "remainder": " Carmen Sandiego?",
    "index": 19
  },
  {
    "match": "Carmen",
    "remainder": " Sandiego?",
    "index": 22
  },
  {
    "match": "Sandiego",
    "remainder": "?",
    "index": 29
  }
]

In order to match multiple occurrences similar to what is available in PHP with preg_match_all you can use this type of thinking to make your own or use something like YourJS.matchAll(). YourJS more or less defines this function as follows:

为了匹配与PHP中使用的preg_match_all相似的多个事件,您可以使用这种类型的思想来创建自己的或使用类似于您的jsm . matchall()。您的js或多或少地定义了以下功能:

function matchAll(str, rgx) {
  var arr, extras, matches = [];
  str.replace(rgx.global ? rgx : new RegExp(rgx.source, (rgx + '').replace(/[\s\S]+\//g , 'g')), function() {
    matches.push(arr = [].slice.call(arguments));
    extras = arr.splice(-2);
    arr.index = extras[0];
    arr.input = extras[1];
  });
  return matches[0] ? matches : null;
}

#9


1  

If you can get away with using map this is a four-line-solution:

如果你能使用地图,这是一个四线解决方案:

var mystring = '1111342=Adam%20Franco&348572=Bob%20Jones';

var result = mystring.match(/(&|&amp;)?([^=]+)=([^&]+)/g) || [];
result = result.map(function(i) {
  return i.match(/(&|&amp;)?([^=]+)=([^&]+)/);
});

console.log(result);

Ain't pretty, ain't efficient, but at least it is compact. ;)

不是很漂亮,不是很有效率,但至少它是紧凑的。,)

#10


0  

To capture several parameters using the same name, I modified the while loop in Tomalak's method like this:

为了使用相同的名称捕获多个参数,我在Tomalak的方法中修改了while循环:

  while (match = re.exec(url)) {
    var pName = decode(match[1]);
    var pValue = decode(match[2]);
    params[pName] ? params[pName].push(pValue) : params[pName] = [pValue];
  }

input: ?firstname=george&lastname=bush&firstname=bill&lastname=clinton

输入:? firstname = george&lastname = bush&firstname = bill&lastname =克林顿

returns: {firstname : ["george", "bill"], lastname : ["bush", "clinton"]}

返回:{firstname: ["george", "bill"], lastname:["布什","克林顿"]

#11


0  

Well... I had a similar problem... I want an incremental / step search with RegExp (eg: start search... do some processing... continue search until last match)

嗯…我有一个类似的问题……我想用RegExp(例如:开始搜索…)做一些处理……继续搜索直到最后一场比赛)

After lots of internet search... like always (this is turning an habit now) I end up in * and found the answer...

经过大量的互联网搜索…像往常一样(现在这已经变成了一种习惯),我最终在*找到了答案……

Whats is not referred and matters to mention is "lastIndex" I now understand why the RegExp object implements the "lastIndex" property

我现在不知道为什么RegExp对象实现了“lastIndex”属性。

#12


0  

Use window.URL:

使用window.URL:

> s = 'http://www.example.com/index.html?1111342=Adam%20Franco&348572=Bob%20Jones'
> u = new URL(s)
> Array.from(u.searchParams.entries())
[["1111342", "Adam Franco"], ["348572", "Bob Jones"]]

#13


0  

Splitting it looks like the best option in to me:

对我来说,分手似乎是最好的选择:

'1111342=Adam%20Franco&348572=Bob%20Jones'.split('&').map(x => x.match(/(?:&|&amp;)?([^=]+)=([^&]+)/))

#1


152  

I would suggest an alternative regex, using sub-groups to capture name and value of the parameters individually:

我建议使用另一个regex,使用子组分别捕获参数的名称和值:

function getUrlParams(url) {
  var re = /(?:\?|&(?:amp;)?)([^=&#]+)(?:=?([^&#]*))/g,
      match, params = {},
      decode = function (s) {return decodeURIComponent(s.replace(/\+/g, " "));};

  if (typeof url == "undefined") url = document.location.href;

  while (match = re.exec(url)) {
    params[decode(match[1])] = decode(match[2]);
  }
  return params;
}

var result = getUrlParams("http://maps.google.de/maps?f=q&source=s_q&hl=de&geocode=&q=Frankfurt+am+Main&sll=50.106047,8.679886&sspn=0.370369,0.833588&ie=UTF8&ll=50.116616,8.680573&spn=0.35972,0.833588&z=11&iwloc=addr");

result is an object:

结果是一个对象:

{
  f: "q"
  geocode: ""
  hl: "de"
  ie: "UTF8"
  iwloc: "addr"
  ll: "50.116616,8.680573"
  q: "Frankfurt am Main"
  sll: "50.106047,8.679886"
  source: "s_q"
  spn: "0.35972,0.833588"
  sspn: "0.370369,0.833588"
  z: "11"
}

The regex breaks down as follows:

regex分解如下:

(?:            # non-capturing group
  \?|&         #   "?" or "&"
  (?:amp;)?    #   (allow "&amp;", for wrongly HTML-encoded URLs)
)              # end non-capturing group
(              # group 1
  [^=&#]+      #   any character except "=", "&" or "#"; at least once
)              # end group 1 - this will be the parameter's name
(?:            # non-capturing group
  =?           #   an "=", optional
  (            #   group 2
    [^&#]*     #     any character except "&" or "#"; any number of times
  )            #   end group 2 - this will be the parameter's value
)              # end non-capturing group

#2


64  

You need to use the 'g' switch for a global search

您需要使用“g”开关进行全局搜索。

var result = mystring.match(/(&|&amp;)?([^=]+)=([^&]+)/g)

#3


34  

If you don't want to rely on the "blind matching" that comes with running exec style matching, JavaScript does come with match-all functionality built in, but it's part of the replace function call, when using a "what to do with the capture groups" handling function:

如果您不想依赖于运行exec风格匹配的“盲匹配”,那么JavaScript将附带所有内置的功能,但它是替换函数调用的一部分,当使用“如何处理捕获组”的处理函数时:

var data = {};

var getKeyValue = function(fullPattern, group1, group2, group3) {
  data[group2] = group3;
};

mystring.replace(/(?:&|&amp;)?([^=]+)=([^&]+)/g, getKeyValue);

done.

完成了。

Instead of using the capture group handling function to actually return replacement strings (for replace handling, the first arg, called a here, is the full pattern match, and subsequent args are individual capture groups, in this case b being group 1, c group 2, etc) we simply take the groups 2 and 3 captures, and cache that pair.

而不是使用捕获组处理函数来返回替换字符串(更换处理,第一个参数,称为,是完整的模式匹配,和随后的arg游戏个人捕捉组,在这种情况下,b组1,c组2,等等)我们只是组2和3了,一对和缓存。

So, rather than writing complicated parsing functions, remember that the "matchAll" function in JavaScript is simply "replace" with a replacement handler function, and much pattern matching efficiency can be had.

因此,与其编写复杂的解析函数,还不如记住JavaScript中的“matchAll”函数仅仅是“替换”替换处理函数,并且可以有许多模式匹配效率。

#4


20  

For capturing groups, I'm used to using preg_match_all in PHP and I've tried to replicate it's functionality here:

对于捕获组,我习惯使用PHP中的preg_match_all,我尝试在这里复制它的功能:

<script>

// Return all pattern matches with captured groups
RegExp.prototype.execAll = function(string) {
    var match = null;
    var matches = new Array();
    while (match = this.exec(string)) {
        var matchArray = [];
        for (i in match) {
            if (parseInt(i) == i) {
                matchArray.push(match[i]);
            }
        }
        matches.push(matchArray);
    }
    return matches;
}

// Example
var someTxt = 'abc123 def456 ghi890';
var results = /[a-z]+(\d+)/g.execAll(someTxt);

// Output
[["abc123", "123"],
 ["def456", "456"],
 ["ghi890", "890"]]

</script>

#5


14  

Set the g modifier for a global match:

为全局匹配设置g修饰符:

/…/g

#6


10  

Source: https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec

来源:https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec

Finding successive matches

If your regular expression uses the "g" flag, you can use the exec() method multiple times to find successive matches in the same string. When you do so, the search starts at the substring of str specified by the regular expression's lastIndex property (test() will also advance the lastIndex property). For example, assume you have this script:

如果正则表达式使用“g”标志,则可以多次使用exec()方法来查找相同字符串中的连续匹配。当您这样做时,搜索从正则表达式的lastIndex属性指定的子字符串开始(test()也将推进lastIndex属性)。例如,假设您有这个脚本:

var myRe = /ab*/g;
var str = 'abbcdefabh';
var myArray;
while ((myArray = myRe.exec(str)) !== null) {
  var msg = 'Found ' + myArray[0] + '. ';
  msg += 'Next match starts at ' + myRe.lastIndex;
  console.log(msg);
}

This script displays the following text:

此脚本显示以下文本:

Found abb. Next match starts at 3
Found ab. Next match starts at 912

Note: Do not place the regular expression literal (or RegExp constructor) within the while condition or it will create an infinite loop if there is a match due to the lastIndex property being reset upon each iteration. Also be sure that the global flag is set or a loop will occur here also.

注意:不要将正则表达式(或RegExp构造函数)放在while条件中,否则将创建一个无限循环,如果有匹配,则将在每次迭代中重置lastIndex属性。同时,也要确保在这里设置了全局标志或循环。

#7


2  

If someone (like me) needs Tomalak's method with array support (ie. multiple select), here it is:

如果有人(像我一样)需要使用数组支持的Tomalak方法。多重选择),这里是:

function getUrlParams(url) {
  var re = /(?:\?|&(?:amp;)?)([^=&#]+)(?:=?([^&#]*))/g,
      match, params = {},
      decode = function (s) {return decodeURIComponent(s.replace(/\+/g, " "));};

  if (typeof url == "undefined") url = document.location.href;

  while (match = re.exec(url)) {
    if( params[decode(match[1])] ) {
        if( typeof params[decode(match[1])] != 'object' ) {
            params[decode(match[1])] = new Array( params[decode(match[1])], decode(match[2]) );
        } else {
            params[decode(match[1])].push(decode(match[2]));
        }
    }
    else
        params[decode(match[1])] = decode(match[2]);
  }
  return params;
}
var urlParams = getUrlParams(location.search);

input ?my=1&my=2&my=things

输入吗?我可做可做= 1 = 2 =

result 1,2,things (earlier returned only: things)

结果1、2、事物(以前只返回:东西)

#8


2  

Just to stick with the proposed question as indicated by the title, you can actually iterate over each match in a string using String.prototype.replace(). For example the following does just that to get an array of all words based on a regular expression:

为了坚持标题所示的建议问题,您实际上可以使用string .prototype.replace()在字符串中迭代每个匹配。例如,下面这样做只是为了得到基于正则表达式的所有单词的数组:

function getWords(str) {
  var arr = [];
  str.replace(/\w+/g, function(m) {
    arr.push(m);
  });
  return arr;
}

var words = getWords("Where in the world is Carmen Sandiego?");
// > ["Where", "in", "the", "world", "is", "Carmen", "Sandiego"]

If I wanted to get capture groups or even the index of each match I could do that too. The following shows how each match is returned with the entire match, the 1st capture group and the index:

如果我想要得到每个匹配的集合或者索引,我也可以这样做。以下显示了每个匹配如何与整个匹配返回,第一个捕获组和索引:

function getWords(str) {
  var arr = [];
  str.replace(/\w+(?=(.*))/g, function(m, remaining, index) {
    arr.push({ match: m, remainder: remaining, index: index });
  });
  return arr;
}

var words = getWords("Where in the world is Carmen Sandiego?");

After running the above, words will be as follows:

在运行上述内容后,将会有以下几个字:

[
  {
    "match": "Where",
    "remainder": " in the world is Carmen Sandiego?",
    "index": 0
  },
  {
    "match": "in",
    "remainder": " the world is Carmen Sandiego?",
    "index": 6
  },
  {
    "match": "the",
    "remainder": " world is Carmen Sandiego?",
    "index": 9
  },
  {
    "match": "world",
    "remainder": " is Carmen Sandiego?",
    "index": 13
  },
  {
    "match": "is",
    "remainder": " Carmen Sandiego?",
    "index": 19
  },
  {
    "match": "Carmen",
    "remainder": " Sandiego?",
    "index": 22
  },
  {
    "match": "Sandiego",
    "remainder": "?",
    "index": 29
  }
]

In order to match multiple occurrences similar to what is available in PHP with preg_match_all you can use this type of thinking to make your own or use something like YourJS.matchAll(). YourJS more or less defines this function as follows:

为了匹配与PHP中使用的preg_match_all相似的多个事件,您可以使用这种类型的思想来创建自己的或使用类似于您的jsm . matchall()。您的js或多或少地定义了以下功能:

function matchAll(str, rgx) {
  var arr, extras, matches = [];
  str.replace(rgx.global ? rgx : new RegExp(rgx.source, (rgx + '').replace(/[\s\S]+\//g , 'g')), function() {
    matches.push(arr = [].slice.call(arguments));
    extras = arr.splice(-2);
    arr.index = extras[0];
    arr.input = extras[1];
  });
  return matches[0] ? matches : null;
}

#9


1  

If you can get away with using map this is a four-line-solution:

如果你能使用地图,这是一个四线解决方案:

var mystring = '1111342=Adam%20Franco&348572=Bob%20Jones';

var result = mystring.match(/(&|&amp;)?([^=]+)=([^&]+)/g) || [];
result = result.map(function(i) {
  return i.match(/(&|&amp;)?([^=]+)=([^&]+)/);
});

console.log(result);

Ain't pretty, ain't efficient, but at least it is compact. ;)

不是很漂亮,不是很有效率,但至少它是紧凑的。,)

#10


0  

To capture several parameters using the same name, I modified the while loop in Tomalak's method like this:

为了使用相同的名称捕获多个参数,我在Tomalak的方法中修改了while循环:

  while (match = re.exec(url)) {
    var pName = decode(match[1]);
    var pValue = decode(match[2]);
    params[pName] ? params[pName].push(pValue) : params[pName] = [pValue];
  }

input: ?firstname=george&lastname=bush&firstname=bill&lastname=clinton

输入:? firstname = george&lastname = bush&firstname = bill&lastname =克林顿

returns: {firstname : ["george", "bill"], lastname : ["bush", "clinton"]}

返回:{firstname: ["george", "bill"], lastname:["布什","克林顿"]

#11


0  

Well... I had a similar problem... I want an incremental / step search with RegExp (eg: start search... do some processing... continue search until last match)

嗯…我有一个类似的问题……我想用RegExp(例如:开始搜索…)做一些处理……继续搜索直到最后一场比赛)

After lots of internet search... like always (this is turning an habit now) I end up in * and found the answer...

经过大量的互联网搜索…像往常一样(现在这已经变成了一种习惯),我最终在*找到了答案……

Whats is not referred and matters to mention is "lastIndex" I now understand why the RegExp object implements the "lastIndex" property

我现在不知道为什么RegExp对象实现了“lastIndex”属性。

#12


0  

Use window.URL:

使用window.URL:

> s = 'http://www.example.com/index.html?1111342=Adam%20Franco&348572=Bob%20Jones'
> u = new URL(s)
> Array.from(u.searchParams.entries())
[["1111342", "Adam Franco"], ["348572", "Bob Jones"]]

#13


0  

Splitting it looks like the best option in to me:

对我来说,分手似乎是最好的选择:

'1111342=Adam%20Franco&348572=Bob%20Jones'.split('&').map(x => x.match(/(?:&|&amp;)?([^=]+)=([^&]+)/))