javascript - 识别纯文本句子中的推特句柄

标签 javascript jquery replace

我需要帮助识别纯文本句子中的 Twitter 句柄(我认为它称为句柄..)并在句柄周围包裹一个 span 标签。

所以如果我有一个这样构造的句子:

I can't wait to watch the 2012 London Olympic Games! @london2012

我需要找到句柄并在其周围包裹一个 span 标签:

I can't wait to watch the 2012 London Olympic Games! <span>@london2012</span>

这是我尝试过的:

function findHandle(text) {
    var handle = text.substr(text.indexOf("@"), text.indexOf(" "));
    return text.replace(handle, "<span>" + handle + "</span>");
}

我的代码没有按计划运行。最好的方法是什么?

最佳答案

假设您的文本内容位于 div 元素中,以下内容似乎有效(尽管未进行详尽测试):

$('div').html(
    function(i,html) {
        return html.replace(/@[\d\D]+\b/g, '<span>$&</span>');
    });​

JS Fiddle demo .

上面似乎是一个little fragile ,所以我将正则表达式选择器更改为:

$('div').html(
    function(i,html) {
        return html.replace(/(@\w+)/g, '<span>$&</span>');
    });​

JS Fiddle demo .

引用资料:

关于javascript - 识别纯文本句子中的推特句柄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11852890/

相关文章:

javascript - JSON = "XXX is Null or not an Object"在 ie6、ie7 中(不是 ie8、FF、Ch)

javascript - NodeJS 将文本缓冲区转换为可查看的 HTML 页面

javascript - 如何修改DIY slider ?

python - 如何根据其他列的某些值替换列的 nan 值

javascript - NodeJS 数据报 - 接收 IPv6 多播

javascript - 如何避免检查对象中的对象是否存在于数据Vue.js中?

jquery - Bootstrap 选项卡中的数据表大小不正确

jQuery,使用 .remove() ,但我希望出现一个确认框

git - 如何使用 Mercurial 为文件执行 "replace with the latest from head"?

javascript - 需要帮助在 Javascript 中重复更新一些文本