phpjquerycsshashtagmention

How to add span element around specific @words


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.


Solution

  • 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>