How to add span element around specific @words

馋奶兔 提交于 2019-12-08 08:16:52

问题


I have user feedback board and I have implemented @mentioning to other users on the site. Once the other user is @mentioned, it shows up in their inbox with a notice that they were "@mentioned on ___ post".

When the post displays, it currently shows the @mention as plain-text - as in:

"Hi @JoeBlow, nice work today..."

However what I want to do is put a <span> element around @mention names to make it blue or somehow make the @mention standout - as in:

Hi <span style="font-color:blue">@JoeBlow</span>, nice work today..."

I am not familiar with regex and I am not even sure if this is the right way.

I don't think this is a CSS thing and would have to be either:

a) Spit out on the fly via PHP
b) Handle with a little jQuery (preferable)

I could go simply by str_replace() and find each @ and try to do some crazy replace text move, however the problem is that each username is not a fixed length. So how would I be able to tell how long each username is to replace with a string wrapped in a <span> element?

Either way, that sounds like a dirty hack.

I would think that some plugin has been made for this by now to implement @mentioning or #hashtaging.

Or possibly it has to be custom made.

Any ideas would be appreciated.


回答1:


A simple jQuery way, split the string by whitespace so you get an array from the text string, then check if any word starting with # or @ then wrap with span and put it back to an array, at the end join the array and output as HTML back.

$('div').each(function() {
  var textArry = $(this).text().split(" ");
  $.each(textArry, function(index) {
    if (textArry[index].match("^#") || textArry[index].match("^@"))
      textArry[index] = '<span class="mention">' + textArry[index] + '</span>';
  });
  var output = textArry.join(' ');
  $(this).html(output);
});
.mention {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>"Hi @JoeBlow, nice work today..."</div>
<div>"Hi @JoeBlow, @JackWhat nice work today..."</div>
<div>"Hi #JoeBlow, nice work today..."</div>
<div>"Hi Joe@Blow, my e-mail is xyz@gmail.com"</div>


来源:https://stackoverflow.com/questions/44296328/how-to-add-span-element-around-specific-words

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