0

Test string is:

hello hello hello

<span class="self-reference">Tom</span> I don't know <span class="self-reference">Tom</span> I don't think.

I wish to to come out as:

hello hello hello

@Tom I don't know @Tom I don't think.

I use this regex:

comment = comment.replace(/\<span class="self-reference"\>(.*)\<\/span\>/gi,"@$1");

But it outputs:

hello hello hello

@Tom</span> I don't know <span class="self-reference">Tom I don't think.

Can anyone tell me how to modify this so it works as expected?

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
Tom Gullen
  • 61,249
  • 84
  • 283
  • 456
  • Obligatory.. http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – James Montagne Sep 12 '12 at 13:59

2 Answers2

3

Use non-greedy regex matching:

comment = comment.replace(/\<span class="self-reference"\>(.*?)\<\/span\>/gi,"@$1");

Without the ? I added, your regex (.*) will match the whole string up to the last </span> it founds in your string. Using non-greedy operator *? you make the match stop as soon as a match is found.

Lazy quantification

The standard quantifiers in regular expressions are greedy, meaning they match as much as they can.

(source)

Community
  • 1
  • 1
sergio
  • 68,819
  • 11
  • 102
  • 123
2

Another possible solution:

comment = comment.replace(/\<span class="self-reference"\>([^<]+)\<\/span\>/gi,"@$1");

([^<]+) captures all chars until < is found

dan-lee
  • 14,365
  • 5
  • 52
  • 77