1

先举例,后问……

示例 1) '?sort=alpha&direction=asc' 的非全局匹配

'?sort=alpha&direction=asc'.match(/([^?&=]+)(=([^&]*))?/);

输出:

// ['sort=alpha', 'sort', '=alpha', 'alpha']

示例 2) '?sort=alpha&direction=asc' 的全局匹配

'?sort=alpha&direction=asc'.match(/([^?&=]+)(=([^&]*))?/g);

输出:

// ['sort=alpha', 'sort', '=alpha', 'alpha']

示例 3) '?sort=alpha&direction=asc' 的全局匹配替换

getRequestParameters: function () {
    var query_string = {},
        regex = new RegExp('([^?=&]+)(=([^&]*))?', 'g');

    '?sort=alpha&direction=asc'.replace(regex, function(match, p1, p2, p3, offset, string) {
        console.log(match, p1, p2, p3, offset, string);

        query_string[p1] = p3;
    });
}

输出:

// sort=alpha sort =alpha alpha 1 ?sort=alpha&direction=asc
// direction=asc direction =asc asc 12 ?sort=alpha&direction=asc 


我的问题

我不确定我是否可以自己解决这个问题,但我从来没有“生活”过一个解决方案,我必须找出原因背后的韵律。我认为“完全足够”理解的具体匹配。我相信我知道下面的一些答案,但我宁愿不做假设并向更聪明的人学习!

  1. 为什么 1) 和 2) 相同?(或者他们是?)
  2. 1) 和 2) 中的“sort=alpha”是什么意思?
  3. 为什么 2) 不返回排序和方向参数?
  4. 3) 使用 .replace() 进行迭代是什么?
  5. 有没有办法在没有 .replace() 的情况下捕获 N 个参数?

谢谢!

更新

var regex = new RegExp('([^?&=]+)(=([^&]*))?');
regex.exec('?sort=alpha&direction=asc');
// Chrome 21 - ["sort=alpha", "sort", "=alpha", "alpha"]

var regex = new RegExp('([^?&=]+)(=([^&]*))?', 'g');
regex.exec('?sort=alpha&direction=asc');
// Chrome 21 - ["sort=alpha", "sort", "=alpha", "alpha"]

'?sort=alpha&direction=asc'.match(/([^?&=]+)(=([^&]*))?/);
// Chrome 21 - ["sort=alpha", "sort", "=alpha", "alpha"]

'?sort=alpha&direction=asc'.match(/([^?&=]+)(=([^&]*))?/g);
// Chrome 21 - ["sort=alpha", "direction=asc"]

var regex = new RegExp('([^?&=]+)(=([^&]*))?', 'g');
regex.lastIndex = 11;
regex.exec('?sort=alpha&direction=asc');
// Chrome 21 - ["direction=asc", "direction", "=asc", "asc"]

总而言之,示例 3)仍然是正确的,但请转到此答案以获得更合格的答案。

结束更新

参考资料并感谢 Steven Benner:

4

1 回答 1

3

先回答,后提问:

  1. In both Chrome 21 and Firefox 14 I get ["sort=alpha", "direction=asc"] for the g version - so they are not the same at all.
  2. The first returned value from match is the entire matched string (in this case one or more characters that are not an ampersand, question mark or equal sign optionally followed by an equal sign and zero or more characters that are not an ampersand).
  3. It does (see answer to #1) - what browser are you running these tests in?
  4. replace is iterating over each match it finds in the string.
  5. Use multiple calls to exec or use the existing regex you have:

    > '?sort=alpha&direction=asc&another=value'.match(/([^?&=]+)(=([^&]*))?/g);
    ["sort=alpha", "direction=asc", "another=value"]
    

What browser are you using that gave you the results you provided for your first questions?

于 2012-08-23T03:08:31.327 回答