我正在使用下面的 javascript 代码尝试提取 gallery-entry_
之后的数字在下面的 html 标记中,尽管我使用了 g
,但它没有给出所有匹配项,而是只返回第一个匹配项正则表达式中的修饰符。知道为什么吗?
<script type="text/javascript">
var _gallery = jQuery('ul.gallery').html();
var _pat = /"gallery-entry_([0-9]+)"/gim;
var _items = _pat.exec(_gallery);
alert('str='+_items[0]); // shows str="gallery-entry_1"
alert('item #1='+_items[1]); // shows item #1=1
alert('total='+_items.length); // shows total=2
</script>
这是标记:
<ul class="gallery">
<li id="gallery-entry_1"><a href="" title=""><img src="" width="116" height="116" alt=""></a></li>
<li id="gallery-entry_2"><a href="" title=""><img src="" width="116" height="116" alt=""></a></li>
<li id="gallery-entry_6"><a href="" title=""><img src="" width="116" height="116" alt=""></a></li>
<li id="gallery-entry_10"><a href="" title=""><img src="" width="116" height="116" alt=""></a></li>
<li id="gallery-entry_14"><a href="" title=""><img src="" width="116" height="116" alt=""></a></li>
<li id="gallery-entry_22"><a href="" title=""><img src="" width="116" height="116" alt=""></a></li>
<li id="gallery-entry_30"><a href="" title=""><img src="" width="116" height="116" alt=""></a></li>
<li id="gallery-entry_31"><a href="" title=""><img src="" width="116" height="116" alt=""></a></li>
</ul>
最佳答案
exec
始终返回一项。
您可以在循环中使用exec
,或者使用String.prototype.match()
。
_gallery.match(_pat);
也就是说,使用正则表达式来获取您想要的数据似乎不是一个很好的选择。
如果您需要 ID,请使用 .map()
。
var _items = $('ul.gallery > li').map(function(i,el) {
return el.id;
}).toArray();
关于javascript - 尽管在 Regex 中使用了全局修饰符,但仅返回一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11174582/