Below code works well, its able to replace any tag it find with a link, but tags with existing links are also replaced, like @google which should be ignored.
<div class="post">
<p class="test">First text some @microsoft</p>
<p class="test">Second text with <a href="http://www.google.com">@google</a>, @yahoo</p>
<p class="test">Third text with @apple, @stackoverflow</p>
</div>
$('.post p.test').each(function (i, el) {
$(el).html($(el).html().replace(/\B\@([\w\-]+)/gim, function (match, username) {
return '<a href="http://www.twitter.com/' + username + '">' + match + '</a>';
}));
});
I have had no luck with regex, I want jquery to ignore tags with existing link: http://jsfiddle.net/ereXZ/1/
You can try a negative lookahead
(?!</a>)after your link regex, see updated jsfiddleNote that the
[\w\-]+has been changed to[\w\-]+\b(?!</a>). The\bmakes sure the regex matches up to the end of the tag, and the(?!</a>)makes sure tags followed by a closing link tag are not matched (and the/needs to be delimited).