问题
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>
回答1:
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.
回答2:
You can also use match()
to search your at
and hash
words.
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>
来源:https://stackoverflow.com/questions/54213292/wrapping-css-class-to-hashtag-content-at-content