0

Found lots of questions about "How to GET the last occurrence of a string" but none about "how to DON'T get it", and this is my problem.

I'm working with emojis and I want to count each emoji (<img>) of the string as one char, so I can get the right length of the string.

When replacing, it finds the beginning (<img), but the last part (>) is being caught at the last occurrence, not the first one, which closes the first <img tag.

This is my code (without unnecessary stuff):

 var typed = $(this).html();

 var matches = typed.match(/\<img.*:"\>/g);
 if (matches != null) {
   for (var i = 0; i < matches.length; i++) {
     console.log('Match ' + i + ': ' + matches[i]);
   }
 }

The log result is this:

Match 0: <img src="/platform/resources/plugins/emoji-area/img/joy.png" class="img" alt=":joy:"><img src="/platform/resources/plugins/emoji-area/img/evil.gif" class="img" alt=":evil:"><img src="/platform/resources/plugins/emoji-area/img/evil.gif" class="img" alt=":evil:">

But it should be:

Match 0: <img src="/platform/resources/plugins/emoji-area/img/joy.png" class="img" alt=":joy:">
Match 1: <img src="/platform/resources/plugins/emoji-area/img/evil.gif" class="img" alt=":evil:">
Match 2: <img src="/platform/resources/plugins/emoji-area/img/evil.gif" class="img" alt=":evil:">

How do I fix it to get each <img> separated?

jpenna
  • 8,426
  • 5
  • 28
  • 36
  • Use [non-greedy repetition](http://www.regular-expressions.info/repeat.html). – Bergi Apr 20 '16 at 16:04
  • Use a `DOM` parser instead and loop over the results. – Jan Apr 20 '16 at 16:05
  • 1
    http://stackoverflow.com/questions/11898998/how-can-i-write-a-regex-which-matches-non-greedy – Lucas Araujo Apr 20 '16 at 16:06
  • And of course, don't forget [this](http://stackoverflow.com/q/1732348/1048572)! What you really want is the [endswith attribute DOM selector](http://api.jquery.com/attribute-ends-with-selector/): `$(this).find('img[alt$=":"]')` – Bergi Apr 20 '16 at 16:08
  • Thank you very much! Nice site Bergi. I can't select the element because I need it as it is, I just need to remove it from the string, but I want it to stay the same, so I can use it elsewhere in the page. Thanks again – jpenna Apr 20 '16 at 17:08

0 Answers0