vkkodali
vkkodali

Reputation: 690

Search for entire word only when using string.includes() in Javascript

I am trying to search whether a string is present inside an array of strings using the string.includes() method as shown below

var theString = "clovers are the best";
var theArray = ["lovers", "loved", "clove", "love", "clovers"];
for (i = 0; i < theArray.length; i += 1) {
  if (theString.includes(theArray[i])) {
    console.log(theArray[i]);
  }
}

The output I get includes "lovers", "clove" and "love" in addition to the expected "clovers." How can I force the search to look for entire string only?

Upvotes: 2

Views: 2915

Answers (2)

enoua5
enoua5

Reputation: 9

It's returning the extras because they are a part of "clovers". My recommendation would be to split the string individual words:

var input = prompt("enter string").split(" ");
unallowed=",.()[]{}-_=+!@#$%^&*~`|\\<>?/\"':;"; //list of not allowed chars
for(i=0; i<input.length; i++)
{
    for(j=0;j<unallowed.length;j++)
    {
        input[i]=input[i].split(unallowed[j]);
        if(typeof(input[i])=="object")
            input[i]=input[i].join("");
    }
    
}
var theArray = ["lovers", "loved", "clove", "love", "clovers"];
for (i = 0; i < theArray.length; i += 1) {
  for(j=0; j<input.length; j++)
      if (input[j].toLowerCase()==theArray[i]) {
        console.log(theArray[i]);
  }
}
edit: fixed a few derps in my code.

Upvotes: -1

Tibrogargan
Tibrogargan

Reputation: 4613

You're testing each element of the array to see if the element is present in the string. You can just test the array to see if a particular string is a member, which is closer to your description of the problem.

    var theString = "clovers";
    var theArray = ["lovers", "loved", "clove", "love", "clovers"];
    var idx = theArray.findIndex( e => e === theString );
    console.log(idx);
    // finding a string done two ways
    idx = theArray.indexOf( theString );
    console.log(idx);

If idx is not -1, the string is present in the array

Upvotes: 2

Related Questions