1

Basically I was playing around with an Steam bot for some time ago, and made it auto-reply when you said things in an array, I.E an 'hello-triggers' array, which would contain things like "hi", "hello" and such. I made so whenever it received an message, it would check for matches using indexOf() and everything worked fine, until I noticed it would notice 'hiasodkaso', or like, 'hidemyass' as an "hi" trigger.

So it would match anything that contained the word even if it was in the middle of a word.

How would I go about making indexOf only notice it if it's the exact word, and not something else in the same word?

I do not have the script that I use but I will make an example that is pretty much like it:

var hiTriggers = ['hi', 'hello', 'yo'];

// here goes the receiving message function and what not, then:

for(var i = 0; i < hiTriggers.length; i++) {
if(message.indexOf(hiTriggers[i]) >= 0) {
bot.sendMessage(SteamID, randomHelloMsg[Math stuff here blabla]); // randomHelloMsg is already defined
}
}

Regex wouldn't be used for this, right? As it is to be used for expressions or whatever. (my English isn't awesome, ikr)

Thanks in advance. If I wasn't clear enough on something, please let me know and I'll edit/formulate it in another way! :)

prk
  • 3,781
  • 6
  • 17
  • 27

2 Answers2

0

You can extend prototype:

String.prototype.regexIndexOf = function(regex, startpos) {
    var indexOf = this.substring(startpos || 0).search(regex);
    return (indexOf >= 0) ? (indexOf + (startpos || 0)) : indexOf;
}

and do:

var foo = "hia hi hello";
foo.regexIndexOf(/hi\b/);

Or if you don't want to extend the string object:

foo.substr(i).search(/hi\b/); 

both examples where taken from the top answers of Is there a version of JavaScript's String.indexOf() that allows for regular expressions?

Community
  • 1
  • 1
fmsf
  • 36,317
  • 49
  • 147
  • 195
0

Regex wouldn't be used for this, right? As it is to be used for expressions or whatever. (my > English isn't awesome, ikr)

Actually, regex is for any old pattern matching. It's absolutely useful for this.

fmsf's answer should work for what you're trying to do, however, in general extending native objects prototypes is frowned upon afik. You can easily break libraries by doing so. I'd avoid it when possible. In this case you could use his regexIndexOf function by itself or in concert with something like:

    //takes a word and searches for it using regexIndexOf
    function regexIndexWord(word){
        return regexIndexOf("/"+word+"\b/");
    }

Which would let you search based on your array of words without having to add the special symbols to each one.

Mallen
  • 262
  • 2
  • 9