我正在寻找一种jQuery方式来查找所有带有其后的内容的标签(#)和at(@)。最后用css类包装它们。
类换行以“#”或“ @”开头,并在如下所示的任何白色空格之前结束。句子中将有多个#和@。
*{
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>
答案 0 :(得分:5)
您可以轻松地使用Javascript .Split()
方法将字符串分成单词,然后搜索第一个字符。例如:
$('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>
注意:我已经使用一种简单的方法完成了此操作。您将需要处理单词以检测它们是字母/数字,而不包含其他字符。
答案 1 :(得分:0)
您还可以使用match()
搜索at
和hash
单词。
let myhtml = $('ul').html();
const mytypes = myhtml.match(/(@|#)+[^\s<\.]+/g);
const myReplace = (mytype) => {
const isat = mytype.includes('@');
const replacestring = `<span class="${isat ? 'at' : 'hash'}">${mytype}</span>`;
myhtml = myhtml.replace(mytype, replacestring);
};
mytypes.forEach(el => myReplace(el));
$('ul').html(myhtml);
.at {
color: red;
}
.hash {
color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>Phone call @Mary #group-project</li>
<li>Buy food and drinks #BBQ.</li>
<li>Discard old computer #home #computer</li>
</ul>