How to add span element around specific @words

2019-06-05 17:28发布

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条回答
男人必须洒脱
2楼-- · 2019-06-05 17:54

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>

查看更多
登录 后发表回答