Layne Mayo
Layne Mayo

Reputation: 39

Non-case sensitive replacement for indexOf()

I am making a chatbot for a website I use. I am in the process of adding a banned words list. I already have it working to where certain users are not allowed to post link. Here is the code for that.

if (text.indexOf("http://") > -1 || text.indexOf("https://") > -1) {
      if (isOwner || isStaff || user === "user") {}
      else if (!isSub) {
        moderation.timeout(name, 5);
        channel.sendMessage(name + ", only subs can post links.");
}

So what I did was pretty much duplicated the above but without the user restrictions and added new words. Here is the code.

if (text.indexOf("http://") > -1 || text.indexOf("https://") > -1) {
      if (isOwner || isStaff || user === "user") {}
      else if (!isSub) {
        moderation.timeout(name, 5);
        channel.sendMessage(name + ", only subs can post links.");
  }
}
 if (text.indexOf("word1") > -1 || text.indexOf("word2") > -1 || text.indexOf("word3") > -1) {
      moderation.timeout(name, 5);
      channel.sendMessage(name + ", please don't be rude.");
}

The link removal works perfectly fine. I don't like that indexof is case sensitive for the word ban list however. Is there a better way of doing this with a function that is not case sensitive?

Upvotes: 1

Views: 1378

Answers (2)

user663031
user663031

Reputation:

You need to normalize the case of both strings, then do indexOf.

function indexOfCaseInsenstive(a, b) {
  a = a.toLowerCase();
  b = b.toLowerCase();

  return a.indexOf(b);
}

Upvotes: 2

Azamantes
Azamantes

Reputation: 1461

Make a list of words, create regexp for it and test the regexp against incoming messages:

const forbiddenWords = ['http://', 'word1', 'word2'];
const regexp = new RegExp(forbiddenWords.join('|'), 'i');

if(regexp.test(message)) {
    // you have a forbidden message.
}

Upvotes: 1

Related Questions