Javascript:在字符串中查找单词 [英] Javascript: find word in string

查看:208
本文介绍了Javascript:在字符串中查找单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

您可以使用拆分一些

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

这篇关于Javascript:在字符串中查找单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆