0

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?

user6931342
  • 145
  • 3
  • 11
  • 1
    There are two distinct questions. _"this code fails to add style to the second..."_ -> [How to replace all occurrences of a string?](https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string); _"it can not add click event to the words"_ - Needs a [mcve] (and possible error messages) for a proper answer. – Andreas Oct 03 '20 at 09:55

1 Answers1

1

you need to remove duplicates from the result returned by findUsers method and instead of using string.replace use string.replaceAll since you are already having unique user values. plus you need to wrap your span tag <span> in anchor tag <a> to make it look like link. please go through the code snippet below which does what you want to accompalish.

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);
  // this is  where you need to remove duplicate from array
  var uniqueusers = users.filter(function(item, i, ar) {
    return ar.indexOf(item) === i;
  });

  if (uniqueusers) {
    for (var i = 0; i < uniqueusers.length; i++) {
      var user = uniqueusers[i].trim();
      //wrapping span in anchor tag  here and use replaceAll instead of replace.
      text = text.replaceAll(user, '<a href=#><span style="color:blue;" onclick="goToProfile(\'' + user + '\')">' +
        user + '</span></a>');
    }

  } // end if 
  return text;
}

var text = document.getElementById('input1');
text.innerHTML = addStyle(text.innerText);
<div id='input1'>
  "hello @user1 and @user2 , how are you @user1 ?";
</div>
sandeep joshi
  • 1,991
  • 1
  • 8
  • 13