Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
177
rated 0 times [  184] [ 7]  / answers: 1 / hits: 36330  / 10 Years ago, mon, august 25, 2014, 12:00:00

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.


More From » substring

 Answers
28

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)
}

[#69666] Thursday, August 21, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
miles

Total Points: 256
Total Questions: 111
Total Answers: 104

Location: Benin
Member since Fri, Mar 24, 2023
1 Year ago
;