将CSS类包装为Hashtag(#)内容&at(@)内容 [英] Wrapping css class to Hashtag(#) content & At(@) content
问题描述
我正在寻找一种jQuery方法,以查找所有带有其后的内容的主题标签(#)和at(@).最后用css类包装它们.
I am looking for a jQuery way to find all hashtag(#) and at(@) with the content followed by. And finally wrap them with a css class.
类换行以#"或"@"开始,并在如下所示的任何白色空格之前结束.句子中将有多个#和@.
The class wrapping start with "#" or "@" and end before any white-sapce like below. There will multiple # and @ in the sentence.
*{
font-family: sans-serif;
}
.at{
background-color: #ffcccb;
color: #bf2025;
padding: 1px 3px;
border-radius: 3px
}
.hash{
background-color: #9bedff;
color: #26477e;
padding: 1px 3px;
border-radius: 3px
}
original content:
<ul>
<li>Phone call @Mary #group-project</li>
<li>Buy food and drinks #BBQ</li>
<li>Discard old computer #home #computer</li>
</ul>
ultimate goal:
<ul>
<li>Phone call <span class="at">@Mary</span> <span class="hash">#group-project</span></li>
<li>Buy food and drinks <span class="hash">#BBQ</span></li>
<li>Discard old computer <span class="hash">#home</span> <span class="hash">#computer</span></li>
</ul>
推荐答案
您可以轻松地使用Javascript .Split()
方法将字符串分成单词,然后搜索第一个字符.例如:
You can easily use the Javascript .Split()
method to separate your strings into words and then search for the first character. For example:
$('li').each(function(e) {
//Get full string as words
var words = $(this).text().split(" ");
for (var i = 0; i < words.length; i++) {
if (words[i].charAt(0) == "#") {
words[i] = "<span class=hashtag >" + words[i] + "</span>";
}
if (words[i].charAt(0) == "@") {
words[i] = "<span class=at >" + words[i] + "</span>";
}
}
$(this).html(words.join(" "));
});
.at {
color: red;
}
.hashtag {
color: blue
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li>I am a #hashtag</li>
<li>Hey @Bill, what's your #dog called?</li>
<li>Try to only process #letters, #numbers, and not #punctuation.</li>
注意:我已经使用一种简单的方法完成了此操作.您将需要处理这些单词以检测它们是字母/数字,而不包含其他字符.
Note: I've done this using a simple method. You will need to process the words to detect they are letters/numbers and not include other characters.
这篇关于将CSS类包装为Hashtag(#)内容&at(@)内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!