I am trying to check if a string contains a particular word, not just a substring.
Here are some sample inputs/outputs:
var str = "This is a cool area!";
containsWord(str, "is"); // return true
containsWord(str, "are"); // return false
containsWord(str, "area"); // return true
The following function will not work as it will also return true for the second case:
function containsWord(haystack, needle) {
return haystack.indexOf(needle) > -1;
}
This also wouldn't work as it returns false for the third case:
function containsWord(haystack, needle) {
return (' ' +haystack+ ' ').indexOf(' ' +needle+ ' ') > -1;
}
How do I check if a string contains a word then?