Javascript:在字符串中查找单词

Mal*_*ala 5 javascript substring cpu-word

Javascript是否有内置函数来查看字符串中是否存在单词?我不是在寻找类似的东西indexOf(),而是:

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
Run Code Online (Sandbox Code Playgroud)

基本上,我想知道我的单词是否出现,但不是另一个单词的一部分.手动实现起来并不难,但我想我会问是否已经有这样的内置函数,因为看起来它会出现很多东西.

elc*_*nrs 14

你可以使用splitsome:

function findWord(word, str) {
  return str.split(' ').some(function(w){return w === word})
}
Run Code Online (Sandbox Code Playgroud)

或者使用带有字边界的正则表达式:

function findWord(word, str) {
  return RegExp('\\b'+ word +'\\b').test(str)
}
Run Code Online (Sandbox Code Playgroud)


kar*_*rel 5

JavaScriptincludes()方法确定字符串是否包含指定字符串的字符。如果字符串包含字符,则此方法返回 true,否则返回 false。

句法:

string.includes(searchvalue, start)
Run Code Online (Sandbox Code Playgroud)

参数值:

参数说明
搜索值 必填。要搜索的字符串
开始 可选。默认0.从哪个位置开始搜索

例子:

Parameter      Description
searchvalue    Required. The string to search for
start          Optional. Default 0. At which position to start the search