在纯文本句子中识别twitter句柄

Den*_*nez 1 javascript jquery replace

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

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

I can't wait to watch the 2012 London Olympic Games! @london2012
Run Code Online (Sandbox Code Playgroud)

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

I can't wait to watch the 2012 London Olympic Games! <span>@london2012</span>
Run Code Online (Sandbox Code Playgroud)

这是我尝试过的:

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

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

Dav*_*mas 6

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

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

JS小提琴演示.

上面看起来有点脆弱,所以我把正则表达式选择器更改为:

$('div').html(
    function(i,html) {
        return html.replace(/(@\w+)/g, '<span>$&</span>');
    });?
Run Code Online (Sandbox Code Playgroud)

JS小提琴演示.

参考文献: