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?

1

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Although it's the exact opposite of greedy :-)
2

Another possible solution:

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.