0

这让我感到困惑,尽管我认为问题很简单。

鉴于这段代码:

var text   = ' url("https://") repeat scroll 0% 0%, url("https://") repeat scroll 0% 0%, url("https://") repeat scroll 0% 0% red';
var result = /(url)/.exec(text);

我得到了["url", "url"]..我期望的结果["url", "url", "url"]

任何解释为什么它只捕获 2 个 url 实例而不是 3 个

谢谢


更新接受的答案

实际上这是我为 HeadJS 重写的 Modernizr 函数的一部分,所以最终函数将是:

function multiplebgs() {
    var ele   = document.createElement('div');
    var style = ele.style;

    style.cssText = 'background:url(https://),url(https://),red url(https://)';

    // If the UA supports multiple backgrounds, there should be three occurrences
    // of the string "url(" in the return value for elemStyle.background
    var result = (style.background || "").match(/url/g);

    return Object.prototype.toString.call( result ) === '[object Array]' && result.length === 3;
}

console.log(multiplebgs());现在将在受支持的浏览器上正确返回 true 。

如果有人看到这方面的其他问题,请发表评论,谢谢!

4

3 回答 3

3

与带有标志match的正则表达式一起使用:g

var text   = ' url("https://") repeat scroll 0% 0%, url("https://") repeat scroll 0% 0%, url("https://") repeat scroll 0% 0% red';
var result = (text || "").match(/url/g);
result // => ["url", "url", "url"]
于 2013-09-13T14:47:53.750 回答
1

使您的正则表达式全局化并match改用。您也不需要捕获组。

var result = text.match(/url/g);

exec与全局标志一起使用时,还可以让您获得所有匹配项,但是exec当您有多个捕获组时更有用。在您的情况下,要使用 exec 获得所有匹配项,您必须执行以下操作:

var matches = [],
    urlRx = /url/g,
    match;

while (match = urlRx.exec(text)) {
    matches.push(match[0]);
}

console.log(matches);
于 2013-09-13T14:51:54.187 回答
1

第二行相当于你的情况:

'url url url'.match(/url/)    // ["url"]
'url url url'.match(/(url)/)  // ["url", "url"]
'url url url'.match(/url/g)   // ["url", "url", "url"]
'url url url'.match(/(url)/g) // ["url", "url", "url"] same as previous line

考虑到/(url)/,括号内的内容相当于称为子模式或组的“子正则表达式”。每个组的捕获方式与整个模式相同,但使用全局标志 ( //g) 时除外。在这种情况下,将忽略组,并且捕获整个模式的次数与在文本中找到的次数一样多。这个例子将更加明确:

'hello world!hello world!'.match(/hello (world)(!)/)
// ["hello world!", "world", "!"]
// [entire pattern, group 1, group 2]

'hello world!hello world!'.match(/hello (world)(!)/g)
// ["hello world!", "hello world!"]
// [entire pattern, entire pattern]

查看有关 javascript 中正则表达式的重要资源:http ://www.javascriptkit.com/javatutors/redev.shtml

于 2013-09-13T15:17:22.047 回答