-1

I want a code to check whole and exact word match :)

So look is not matching looked in my logic.

let speech = "you ever looked at someone";
let a = "look";

if(speech.includes(a)){
  console.log("Whole Word Matches")
} else {
  console.log("No Match!")
}

How can I modify the code above to check the whole word match

Sara Ree
  • 3,417
  • 12
  • 48
  • that's a task for old good regex. Grab a book and learn about Regular Expressions and try `/\blook\b/gi` – PA. Oct 24 '19 at 15:06
  • [This is the list of results](https://www.google.com/search?q=Check+for+whole+and+exact+word+match+javascript+site:stackoverflow.com) when searching for the exact title of your question. Please read:[How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/a/261593/3082296) – adiga Oct 24 '19 at 15:17

2 Answers2

-1
if(new RegExp("\\b"+a+"\b").test(speech)){
 console.log("Whole Word Matches")
} else {
  console.log("No Match!")
}
Finn
  • 57
  • 3
-2

You can use regular expression (\bregExp\b) to find the exact match of the word.

The \b metacharacter is used to find a match at the beginning or end of a word.

let speech = "you ever looked at someone";
let a = "look";

if(new RegExp("\\b"+a+"\\b").test(speech)){
  console.log("Whole Word Matches")
} else {
  console.log("No Match!")
}
Amit
  • 1,540
  • 1
  • 15
  • 28
  • 1
    code-only answers are not helpflu, you should include some explanation in your answer – PA. Oct 24 '19 at 15:07