2016-11-18 52 views

回答

0

$('p:contains("#")').each(function() { 
 
    var tags = $(this).text().split(' '); 
 
    var wrapped_tags = ''; 
 

 
    tags.forEach(function(tag) { 
 
     wrapped_tags += '<span class="someClass">'+tag+'</span> '; 
 
    }); 
 

 
    $(this).html(wrapped_tags); 
 
});
.someClass { 
 
    color:red; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<p>#tag1 #tag2</p>

+0

這也將包裹非「標籤」(雖然不明確的問題開始的任何字如果只有標籤或混合) –

+0

@ freedomn -m是的,我認爲op意味着有很多pharagraps,其中一些只有裏面的標籤 – Sojtin

+0

@ freedomn-m無論如何,您的答案是更好 – Sojtin

2

您可以使用.html()以及通過當前值的回調並使用正則表達式:

#\w+\b 

這意味着:匹配以#

$("p").html(function(index, html) { 
 
     return html.replace(/(\#\w+\b)/g, "<span>$1</span>") 
 
     }); 
 
     
span { color: orange }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<p>#tag1 #tag2</p> 
 
<p>Here's another #tag3</p>