下面的代碼效果很好,它可以用鏈接替換它找到的任何標籤,但帶有現有鏈接的標籤也會被替換,比如應忽略的@google。不要替換現有的網址正則表達式
<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>';
}));
});
我曾與正則表達式沒有運氣,我希望jQuery忽略與現有的鏈接標籤:使用contentshttp://jsfiddle.net/ereXZ/1/
謝謝,這非常有用。 – Cindro 2012-03-04 10:21:08