I have the following text:
var text = "hello @user1 and @user2 , how are you @user1 ?";
I want to add style to all words that start with '@' and also add click event to them to call a function. here is my code:
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;
}
this code fails to add style to the second '@user1' and also it can not add click event to the words. is there a more efficient way to do this?