Sanchez Panza
Sanchez Panza

Reputation: 381

Searching for exact string within a string with String.includes()

I am trying to search for exact string/word within a string/sentence with includes() and I want it to return true if it does. But I get returned "true" even if word matches part of a bigger word. How do I approach searching for exact match? I realize that includes() is case sensetive but I want it to be length sensitive so to say, I understand I should probably somehow define what a word in a string for js is but not sure how to do it with includes(). Thanks

var sentence = 'The quick brown fox jumps over the lazy dog.';
var word = 'own';
console.log(`The word "${word}" ${sentence.includes(word)? 'is' : 'is not'} in the sentence`);

// wanted output: "The word "own" is not in the sentence"
// real output: "The word "own" is in the sentence"

Upvotes: 2

Views: 2032

Answers (4)

Sebin Thankachan
Sebin Thankachan

Reputation: 1

If the word is not coming in the start or end of the sentence you can just add space

var word = ' own ';

then you can get an exact match with same include function

Upvotes: 0

Code Maniac
Code Maniac

Reputation: 37755

includes tries to search any sequence which matches the passed string ( parameter ), in this case brown has own in it so it returns true, where as you want it to match only when exact word own is found you can use search and regex,

var sentence = 'The quick brown fox jumps over the lazy dog.';

let wordFounder = word => {
  let reg = new RegExp(`\\b${word}\\b`)
  console.log(`The word "${word}" is ${sentence.search(reg) !== -1 ? '' : 'not'} 
in the sentence`);  
}

wordFounder("own")
wordFounder("brown")

Upvotes: 2

MinusFour
MinusFour

Reputation: 14423

You could break it into words and then use Array.prototype.includes:

var sentence = 'The quick brown fox jumps over the lazy dog.';
var word = 'own';
console.log(`The word "${word}" ${sentence.match(/\b\S+\b/g).includes(word)? 'is' : 'is not'} in the sentence`);

sentence.match(/\b\S+\b/g) basically breaks your sentence in an array like:

["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]

And then includes just searches for the word there.

Upvotes: 0

Dominik Matis
Dominik Matis

Reputation: 2146

Use this

const result = sentence.search(word) != -1;

Upvotes: 0

Related Questions