如何在文本内容周围添加HTML标签

How to add HTML tags around text contents?

本文关键字:周围 添加 HTML 标签 文本      更新时间:2023-09-26

我有一个包含两个或两个以上标签的段落:

<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>