Wrapping css class to Hashtag(#) content & At(@) content [closed]

走远了吗. 提交于 2021-02-08 12:12:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!