Well, it seems that you want to search for entire words, not strings.
Here's one approach that should suffice (although isn't fullproof).
Split the string into tokens based on whitespace or punctuation, this should give you a list of words (with some possible empty strings).
Now, if you want to check if your desired word exists in this list of words, you can use the includes method on the list.
console.log(
"This is a pencil."
.split(/\s+|\./) // split words based on whitespace or a '.'
.includes('is') // check if words exists in the list of words
)
If you want to count occurrences of a particular word, you can filter this list for the word you need. Now you just take the length of this list and you'll get the count.
console.log(
"This is a pencil."
.split(/\s+|\./) // split words based on whitespace or a '.'
.filter(word => word === 'is')
.length
)
This approach should also handle words at the beginning or the end of the string.
console.log(
"This is a pencil."
.split(/\s+|\./) // split words based on whitespace or a '.'
.filter(word => word === 'This')
.length
)
Alternatively, you could also reduce the list of words into the number of occurences
console.log(
"This is a pencil."
.split(/\s+|\./) // split words based on whitespace or a '.'
.reduce((count, word) => word === 'is' ? count + 1 : count, 0)
)