简体   繁体   English

Javascript:在字符串中查找单词

[英]Javascript: find word in string

Does Javascript have a built-in function to see if a word is present in a string? Javascript 是否有内置函数来查看字符串中是否存在某个单词? I'm not looking for something like indexOf() , but rather:我不是在寻找像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

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.手动实现不会太难,但我想我会问一下是否已经有这样的内置函数,因为它似乎会出现很多。

You can use split and some :您可以使用splitsome

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

No there is not a built in function for this.不,没有为此内置功能。 You will have to add programming such as a regex or split() it by whitespace then compare the result == 'test'.您必须通过空格添加诸如正则表达式或 split() 之类的程序,然后比较结果 == 'test'。

Moderns browsers have the Array.prototype.includes() , which determines whether an array includes a certain value among its entries, returning true or false as appropriate.现代浏览器具有Array.prototype.includes() ,它确定数组是否在其条目中包含某个值,并根据需要返回truefalse

Here's an example:下面是一个例子:

 const ShoppingList = ["Milk", "Butter", "Sugar"]; console.log(`Milk ${ShoppingList.includes("Milk") ? "is" : "is not"} in the shopping list.`); console.log(`Eggs ${ShoppingList.includes("Eggs") ? "is" : "is not"} in the shopping list.`)

The JavaScript includes() method determines whether a string contains the characters of a specified string. JavaScript contains includes()方法确定字符串是否包含指定字符串的字符。 This method returns true if the string contains the characters, and false if not.如果字符串包含字符,则此方法返回 true,否则返回 false。

Syntax:句法:

string.includes(searchvalue, start)

Parameter values:参数值:

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

Example:例子:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM