Only one item returned despite global modifier use in Regex
-
16-06-2021 - |
Domanda
I'm using the javascript code below trying to extract the number after gallery-entry_
in the html markup below but instead of giving all matches it only returns the first one despite my use of the g
modifier in the regex. Any idea why ?
<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>
Here's the markup:
<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>
Soluzione
exec
always returns one item.
You can use exec
in a loop, or use String.prototype.match()
instead.
_gallery.match(_pat);
That said, it doesn't seem like a very good choice to use a regex to get the data you want.
If you want the IDs, use .map()
.
var _items = $('ul.gallery > li').map(function(i,el) {
return el.id;
}).toArray();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow