Javascript:在字符串中查找单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25493984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript: find word in string
提问by Mala
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:
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
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.
本质上,我想知道我的词是否出现,而不是作为另一个词的一部分。手动实现不会太难,但我想我会问一下是否已经有这样的内置函数,因为它似乎会出现很多。
回答by elclanrs
You can use split
and some
:
您可以使用split
和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)
}
回答by Jeff Clayton
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'。