[英]How to add HTML tags around text contents?
我有一個帶有2個或更多標簽的段落:
<p>#tag1 #tag2</p>
現在,我想找到所有標簽並像這樣包裝它們:
<p><span class="someClass">#tag1</span> <span class="someClass">#tag2</span></p>
您可以將.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>
$('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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.