Javascript:在字符串中查找单词

时间:2014-08-25 20:37:05

标签: javascript substring 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

基本上,我想知道我的单词是否出现,但不是另一个单词的一部分。手动实现起来并不难,但我想我要问看看是否已经有这样的内置功能,因为看起来它似乎是某种东西出现了很多。

4 个答案:

答案 0 :(得分:13)

您可以使用splitsome

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

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

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

答案 1 :(得分:1)

没有内置功能。你必须通过空格添加诸如正则表达式或split()之类的编程,然后比较结果=='test'。

答案 2 :(得分:0)

现代的浏览器具有Array.prototype.includes(),它确定数组的条目中是否包含某个值,并根据需要返回function_Triggered()function setTrigger() { deleteTriggers(); scheduledTrigger(7,55); } function scheduledTrigger(hours,minutes){ var today_D = new Date(); var year = today_D.getFullYear(); var month = today_D.getMonth(); var day = today_D.getDate(); pars = [year,month,day,hours,minutes]; var scheduled_D = new Date(...pars); var hours_remain=Math.abs(scheduled_D - today_D) / 36e5; ScriptApp.newTrigger("function_Triggered") .timeBased() .after(hours_remain * 60 *60 * 1000) .create() } function deleteTriggers() { var triggers = ScriptApp.getProjectTriggers(); for (var i = 0; i < triggers.length; i++) { if ( triggers[i].getHandlerFunction() == "function_Triggered") { ScriptApp.deleteTrigger(triggers[i]); } } } function function_Triggered() { // your function code here }

这是一个例子:

true

答案 3 :(得分:0)

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

语法:

string.includes(searchvalue, start)

参数值:

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

示例:

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`);