如何在特定的@words周围添加span元素 [英] How to add span element around specific @words

查看:124
本文介绍了如何在特定的@words周围添加span元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有用户反馈委员会,并且已对网站上的其他用户实施@提及.一旦提及其他用户,@@@便会显示在其收件箱中,并通知他们在___ post上提到了@".

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".

帖子显示时,它当前将@mention显示为纯文本-如下所示:

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

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

但是我想做的是在@mention名称周围放置一个<span>元素以使其变蓝或以某种方式使@mention脱颖而出-如下所示:

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.

我不认为这是CSS的事情,而必须是:

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

a)通过PHP快速吐出
b)处理一些jQuery(首选)

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

我可以简单地按str_replace()并找到每个@并尝试执行一些疯狂的替换文本移动,但是问题是每个用户名都不是固定长度.那么我如何才能分辨每个用户名用换成<span>元素的字符串替换的时间?

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.

我认为目前已经为此制作了一些插件来实现@mentioning或#hashtaging.

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

或者可能必须定制.

任何想法都会受到赞赏.

Any ideas would be appreciated.

推荐答案

一种简单的jQuery方法,用空格分隔字符串,以便从文本字符串中获取数组,然后检查是否有以#或@开头的单词,然后以跨度并将其放回数组,最后加入数组并以HTML格式输出.

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>

这篇关于如何在特定的@words周围添加span元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆