为以特定字母开头的单词添加样式,并使其在javascript中可单击

为以特定字母开头的单词添加样式,并使其在javascript中可单击,javascript,jquery,regex,Javascript,Jquery,Regex,我有以下案文: var text = "hello @user1 and @user2 , how are you @user1 ?"; 我想为所有以“@”开头的单词添加样式,并向它们添加单击事件以调用函数。这是我的密码: function findUsers(text) { return text.match(/(?:^|\W)@(\w+)(?!\w)/g); } function goToProfile(user) { console.log(&quo

我有以下案文:

var text = "hello @user1 and @user2 , how are you @user1 ?";
我想为所有以“@”开头的单词添加样式,并向它们添加单击事件以调用函数。这是我的密码:

function findUsers(text) {
    return text.match(/(?:^|\W)@(\w+)(?!\w)/g);
}

function goToProfile(user) {
    console.log("go to " + user + " profile.");
}

function addStyle(text) {
    var users = findUsers(text);
    if (users) {
        for(var i = 0; i < users.length; i++) {
            var user = users[i];
            text = text.replace(user
            , '<span style="color:blue;" onclick="goToProfile(\'' + user + '\')">' 
                    + user + '</span>');
        }
       
    }// end if 
    return text;   
 }
函数查找器(文本){
返回text.match(/(?:^|\W)@(\W+(!\W)/g);
}
函数goToProfile(用户){
log(“转到”+user+“profile”);
}
函数addStyle(文本){
var用户=findUsers(文本);
如果(用户){
对于(var i=0;i

此代码无法将样式添加到第二个“@user1”,也无法将单击事件添加到单词中。有更有效的方法吗?

您需要从
findUsers
方法返回的结果中删除重复项,而不是使用
string.replace
使用
string.replaceAll
,因为您已经拥有唯一的用户值。另外,您需要将span标记
包装在锚定标记
');
}
}//如果结束,则结束
返回文本;
}
var text=document.getElementById('input1');
text.innerHTML=addStyle(text.innerText)

“你好@user1和@user2,你好吗@user1?”;

有两个截然不同的问题。“此代码无法将样式添加到第二个…”->;“它无法将单击事件添加到单词中”-需要一个正确答案(以及可能的错误消息)。