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
  • 71,299
  • 12
  • 93
  • 154
Tom Gullen
  • 59,517
  • 82
  • 274
  • 446
  • 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,479
  • 11
  • 101
  • 120
2

Another possible solution:

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

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

dan-lee
  • 14,094
  • 5
  • 50
  • 76