Layne Mayo Layne Mayo - 5 months ago 10
Javascript Question

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?

Answer

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);
}
Comments