简体   繁体   English

检查字符串是否包含单词(不是子字符串)

[英]Check if string contains word (not substring)

I am trying to check if a string contains a particular word, not just a substring. 我正在尝试检查字符串是否包含特定单词,而不仅仅是子字符串。

Here are some sample inputs/outputs: 以下是一些示例输入/输出:

var str = "This is a cool area!";
containsWord(str, "is"); // return true
containsWord(str, "are"); // return false
containsWord(str, "area"); // return true

The following function will not work as it will also return true for the second case: 以下函数将不起作用,因为在第二种情况下也会返回true:

function containsWord(haystack, needle) {
     return haystack.indexOf(needle) > -1;
}

This also wouldn't work as it returns false for the third case: 这也行不通,因为在第三种情况下它返回false:

function containsWord(haystack, needle) {
     return (' ' +haystack+ ' ').indexOf(' ' +needle+ ' ') > -1;
}

How do I check if a string contains a word then? 如何检查字符串中是否包含单词?

Try using regex for that, where the \\b metacharacter is used to find a match at the beginning or end of a word. 为此,请尝试使用正则表达式,其中\\b元字符用于在单词的开头或结尾查找匹配项。

 var str = "This is a cool area!"; function containsWord(str, word) { return str.match(new RegExp("\\\\b" + word + "\\\\b")) != null; } console.info(containsWord(str, "is")); // return true console.info(containsWord(str, "are")); // return false console.info(containsWord(str, "area")); // return true 

 $(function(){ function containsWord(haystack, needle) { return haystack.replace(/[^a-zA-Z0-9 ]/gi, '').split(" ").indexOf(needle) > -1; } var str = "This is a cool area!"; console.log(containsWord(str, "is")); // return true console.log(containsWord(str, "are")); // return false console.log(containsWord(str, "area")); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

You can remove all special characters and then split string with space to get list of words. 您可以删除所有特殊字符,然后用空格分割字符串以获取单词列表。 Now just check id searchValue is in this word list 现在只需检查id searchValue在此单词列表中

 function containsWord(str, searchValue){ str = str.replace(/[^a-z0-9 ]/gi, ''); var words = str.split(/ /g); return words.indexOf(searchValue) > -1 } var str = "This is a cool area!"; console.log(containsWord(str, "is")); // return true console.log(containsWord(str, "are")); // return false console.log(containsWord(str, "area")); // return true 

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

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