Reputation: 14823
Does Javascript have a built-in function to see if a word is present in a string? I'm not looking for something like indexOf()
, but rather:
find_word('test', 'this is a test.') -> true
find_word('test', 'this is a test') -> true
find_word('test', 'I am testing this out') -> false
find_word('test', 'test this out please') -> true
find_word('test', 'attest to that if you would') -> false
Essentially, I'd like to know if my word appears, but not as part of another word. It wouldn't be too hard to implement manually, but I figured I'd ask to see if there's already a built-in function like this, since it seems like it'd be something that comes up a lot.
Upvotes: 15
Views: 47007
Reputation: 5862
The JavaScript includes()
method determines whether a string contains the characters of a specified string. This method returns true if the string contains the characters, and false if not.
Syntax:
string.includes(searchvalue, start)
Parameter values:
Parameter Description searchvalue Required. The string to search for start Optional. Default 0. At which position to start the search
Example:
const sentence = 'The quick brown fox jumps over the lazy dog.';
const word = 'fox';
console.log(`The word "${word}" ${sentence.includes(word) ? 'is' : 'is not'} in the sentence`);
Upvotes: 5
Reputation: 39
Moderns browsers have the Array.prototype.includes()
, which determines whether an array includes a certain value among its entries, returning true
or false
as appropriate.
Here's an example:
const ShoppingList = ["Milk", "Butter", "Sugar"];
console.log(`Milk ${ShoppingList.includes("Milk") ? "is" : "is not"} in the shopping list.`);
console.log(`Eggs ${ShoppingList.includes("Eggs") ? "is" : "is not"} in the shopping list.`)
Upvotes: -1
Reputation: 94101
You can use split
and some
:
function findWord(word, str) {
return str.split(' ').some(function(w){return w === word})
}
Or use a regex with word boundaries:
function findWord(word, str) {
return RegExp('\\b'+ word +'\\b').test(str)
}
Upvotes: 26