避免在 html 标签元素中为相同的主题标签使用空包装

Avoid empty wrappers for same hashtags in a html label element

我创建了自定义 Javascript/JQuery 代码来查找出现在 html 标签中的字符串中的主题标签。我正在突出显示这些主题标签并在它们周围添加包装。但是,如果相同的主题标签字符串显示在 2 个标签中,则在主题标签前面添加了一个奇怪的空包装,并出现在标签内容中。如何避免出现空包装,这是搜索主题标签字符串的好主意,还是会影响网站加载速度?

这是我的代码,用于在字符串中拆分主题标签并在它们周围添加包装器:

$(document).ready(function(event){
    $status_hash = $('.hashtag').text();

    var tagslistarr = $status_hash.split(' ');
    var arr=[];
    $.each(tagslistarr,function(i,val){
        if(tagslistarr[i].indexOf('#') == 0){
          arr.push(tagslistarr[i]);  
        }
    });

    for($x=0; $x<=arr.length;$x++){
        $(".hashtag:contains('"+arr[$x]+"')").html(function(_, html) {
        return html.split(arr[$x]).join("<a href='#' class='smallcaps' style='text-decoration:none; background-color:rgba(113, 162, 252, 0.63); color:white; padding:2px 4px 2px 4px; border-radius:2px;'>"+arr[$x]+"</a>");
        });
    }
});

Jsfiddle(已更新)

Demo: http://jsfiddle.net/Nishan152/ptwmjcep/

尝试

$(".hashtag").map(function(i, el) {
    $(el).html(function(_, html) {
        return html.replace(/(#\w+)/g, function(match) {
          return "<a href=# class=smallcaps "
          + "style=text-decoration:none;"
          + "background-color:rgba(113,162,252,0.63);"
          + "color:white;padding:2px 4px 2px 4px;"
          + "border-radius:2px;>" + match + "</a>"
        })
    })
});

jsfiddle http://jsfiddle.net/guest271314/ptwmjcep/15/

String.prototype.replace() , .html()

您可能不需要那么多操作来进行这种包装或仅提取散列标签。

要获取散列标签,您可以使用这一行:

var arr = $.grep( $('.hashtag').text().split(' '), function( v, i ) {
    return v.charAt(0) === '#';
});

但如果您只想在此处包装标签,请使用代码:

$(document).ready(function(event){
    $('.hashtag').html(function(_,html) {
        return html.replace(/(\#[a-z]+)/gi, function(x) {
            return "<a href='#' class='smallcaps' style='text-decoration:none; background-color:rgba(113, 162, 252, 0.63); color:white; padding:2px 4px 2px 4px; border-radius:2px;'>" + x + "</a>";
        });
    });
});

DEMO