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

Identifying twitter handle in a plain text sentence

本文关键字:句柄 文本 句子 识别      更新时间:2023-09-26

我需要帮助识别纯文本句子中的 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小提琴演示。

上面似乎有点脆弱,所以我将正则表达式选择器更改为:

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

JS小提琴演示。

引用:

  • html() .
  • JavaScript 正则表达式,在 Mozilla 开发者网络。
  • string.replace() .