Javascript: find a word in a string

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 would like to know if my word appears, but not as part of another word. It would not be too difficult to implement manually, but I decided that I would ask to see if there is already a built-in function like this, since it seems that it will be something much.

+4
source share
2 answers

You can use splitand some:

function findWord(word, str) {
  return str.split(' ').some(function(w){return w === word})
}

Or use a regex with layers:

function findWord(word, str) {
  return RegExp('\\b'+ word +'\\b').test(str)
}
+11
source

, . , split(), , == 'test'.

+1

All Articles