This code is to be integrated into an AJAX Chat system to enable a tab auto-completion of user names:
var usernames = new Array();
usernames[0] = "Saladin";
usernames[1] = "Jyllaby";
usernames[2] = "CadaverKindler";
usernames[3] = "qbsuperstar03";
var text = "Text and something else q";
// Start of the script to be imported
var searchTerm = text.slice(text.lastIndexOf(" ") + 1);
var i;
for(i = 0; i < usernames.length && usernames[i].substr(0,searchTerm.length) != searchTerm; i++);
// End of the script to be imported
document.write(usernames[i]);
A couple of notes to be made: The array of usernames and the text variable would both be loaded from the chat itself via AJAX (which, unfortunately, I don’t know), and the final output will be handled by AJAX as well.
Is there a more efficient way to do this?
Also, any tips on how to handle multiple instances of the searchTerm being found?
Micro-optimization: instead of getting the substring and comparing it (creating lots of temporary strings)…
…you should use indexOf, which creates no temporary strings…
What do you mean by “multiple instances of the searchTerm being found”? Can you give an example of the problem you’re thinking of?