Reputation: 7060
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?
Upvotes: 2
Views: 5038
Reputation: 4142
Try using regex for that, where the \b
metacharacter is used to find a match at the beginning or end of a word.
var str = "This is a cool area!";
function containsWord(str, word) {
return str.match(new RegExp("\\b" + word + "\\b")) != null;
}
console.info(containsWord(str, "is")); // return true
console.info(containsWord(str, "are")); // return false
console.info(containsWord(str, "area")); // return true
Upvotes: 7
Reputation: 1799
$(function(){
function containsWord(haystack, needle) {
return haystack.replace(/[^a-zA-Z0-9 ]/gi, '').split(" ").indexOf(needle) > -1;
}
var str = "This is a cool area!";
console.log(containsWord(str, "is")); // return true
console.log(containsWord(str, "are")); // return false
console.log(containsWord(str, "area"));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 2
Reputation: 24915
You can remove all special characters and then split string with space to get list of words. Now just check id searchValue is in this word list
function containsWord(str, searchValue){
str = str.replace(/[^a-z0-9 ]/gi, '');
var words = str.split(/ /g);
return words.indexOf(searchValue) > -1
}
var str = "This is a cool area!";
console.log(containsWord(str, "is")); // return true
console.log(containsWord(str, "are")); // return false
console.log(containsWord(str, "area")); // return true
Upvotes: 4