0

I have been playing around with a pokemon API for a couple of days.

I have an array with all pokemon listed and have a string that looks something like this '<@user_id pidgeotto>'

I would like to check this string, against an array and get that EXACT name

My issue is that I ALSO get things that would be included, like pidgeot.

How can I match the array exactly to the string and ONLY log the one name?

let pokemonArray = ["pidgeot", "pidgeotto", "charizard", "goldeen"];

let y = '<@user_id> pidgeotto';

function handleMessage(message) {
  for (let i = 0; i <= message.length; i++) {
    if (y.includes(message[i])) {
      console.log(message[i])
    }
  }
}

handleMessage(pokemonArray);

No errors, just not getting the result I am looking for.

adiga
  • 34,372
  • 9
  • 61
  • 83
JaySnel
  • 163
  • 2
  • 12
  • 1
    Instead of `includes` you can use `==` operator. If the letter casing are different you can convert to same case before comparing. – random Jul 21 '19 at 15:53
  • Possible duplicate of [Search whole word in string](https://stackoverflow.com/questions/18740664/search-whole-word-in-string) – adiga Jul 21 '19 at 15:55
  • `if(new RegExp('\\b' + message[i] + '\\b', "i").test(y)) { }` – adiga Jul 21 '19 at 15:57
  • @adiga That is not safe if the use has control over message. They could have `|.*` at the end of the message, or they could perform a ReDOS attack by causing catastrophic backtracking – Paul Jul 21 '19 at 16:15
  • @Paulpro the duplicate has an `escapeRegExp` method as well. – adiga Jul 21 '19 at 16:18

3 Answers3

2

Split the y string at the space and see if second part is exact using === comparison

let pokemonArray = ["pidgeot", "pidgeotto", "charizard", "goldeen"];

let y = '<@user_id> pidgeotto';
let yName = y.split(' ')[1];

function handleMessage(message) {
  for (let i = 0; i <= message.length; i++) {
    if (message[i] === yName ) {
      console.log(message[i])
    }
  }
}

handleMessage(pokemonArray);
charlietfl
  • 170,828
  • 13
  • 121
  • 150
0

you could do it by this way to avoid the first element in PokemonArray

let pokemonArray = ["pidgeot", "pidgeotto", "charizard", "goldeen"];

let y = '<@user_id> pidgeotto';

function handleMessage(message) {
    for(let i = 0; i <= message.length; i++) {
        let splitedY = y.split(message[i])
        if(splitedY.length > 1 && splitedY[1] !== "") {
           console.log(message[i])
        }
    }
}

handleMessage(pokemonArray);
Nemer
  • 667
  • 1
  • 6
  • 10
0

Here is the one liner for this:

const match = pokemonArray.find(pokemon => new RegExp(`\\b${pokemon}\\b`, `i`).test(y));

Simply use array find method and match your string using regex. Hope this helps :)

Mohammed Amir Ansari
  • 2,311
  • 2
  • 12
  • 26