Ad

Alternative To Message.content.startWith

- 1 answer

I'm working with a discord bot and I'm doing a help command with pages.

I have this set up:

if(message.content.startWith(`${prefix}help`))

and

if(message.content.startWith(`${prefix}help 2`))

If i do >help 2 I get both. Is there any way to stop that from happening?

Ad

Answer

When using startsWith(">help") (not startWith) it will match ">help 2" because that string does indeed start with ">help". If you want to match these cases more precisely you should put the most specific cases first and use else if for subsequent comparisons.

if (message.content.startsWith(`${prefix}help 2`)) { /* do 2 */ }
else if (message.content.startsWith(`${prefix}help 3`)) { /* do 3 */ }
else if (message.content.startsWith(`${prefix}help 4`)) { /* do 4 */ }
else if (message.content.startsWith(`${prefix}help`)) { /* do other */ }
else if (message.content.startsWith(`${prefix}faq`)) { /* do faq */ }

The code above will only match the second case if the first didn't match.

Further explanation: When comparing partial strings you need to be careful that you're matching the correct thing. Look at this example:

let names = [ "Roberta", "Robert" ]
// case #1 - fails (wrong order)
names.forEach(name => {
  let salutation;
  if (name.startsWith("Robert")) 
    salutation = "Mr.";
  else if (name.startsWith("Roberta")) 
    salutation = "Miss";
  console.log("1) "+salutation+" "+name);
})

// case #2 - fails (missing else)
names.forEach(name => {
  let salutation;
  if (name.startsWith("Roberta")) 
    salutation = "Miss";
  if (name.startsWith("Robert")) 
    salutation = "Mr.";
  console.log("2) "+salutation+" "+name);
})

// case #3 - works
names.forEach(name => {
  let salutation;
  if (name.startsWith("Roberta")) 
    salutation = "Miss";
  else if (name.startsWith("Robert")) 
    salutation = "Mr.";
  console.log("3) "+salutation+" "+name);
})

Case #1 fails because both names match on the first if-statement because both names actually do start with "Robert". But we didn't want it to match "Roberta" because we have a second check for that start of the string. However the code never went into the second if-statement because it already matched on the first one. By reversing the order of checking and putting the check for "Roberta" first we get the right behaviour because it's more specific ('Robert' doesn't start with 'Roberta' but 'Roberta' does start with 'Robert'). So the important part is to order your if-statements to match with the most specific before the more general values.

Case #2 fails because even if the first if-statement matches, the second one can also match. We want to use else if to make sure that if something earlier in the code has already matched that we don't keep checking other cases.

Ad
source: stackoverflow.com
Ad