How to get word that is after indexOf(“@”) and add it to array

as the manual states indexOf takes a second parameter, instructing the function to search starting from specific position. So when you want to extract the word after the @ sign you are lookign for the portion of text between @ and the next space eg

hello @valerj how are you
      ^      ^
      p1     p2

so you would use

p1   = str.indexOf('@');
p2   = str.indexOf(' ',p1);
name = str.substr(p1,p2-p1); //substr want start and length

yet as you see it would fail on a lot of strings like

hello @valerij, how are you
ping @valerij
             ^line end

you could adress this issue by using regex to obtain the p2 eg

p2   = str.indexOf(/ ,.?!$/,p1);

but it might still fail. The best solution would be to use regex for all the operation eg

var myregexp = /@(\w+)\b/;

(the \b is word boundary and will take care of all punctuation, line endings and other characters)
and use this code

var userNames = [];
var match = myregexp.exec(str);
while (match != null) {
    //username is in match[1] (first capturing group)
    userNames.push(match[1]);
    match = myregexp.exec(subject);
}

to populate the array with usernames mentioned in the chat message

Leave a Comment