简体   繁体   English

如何检查字符串是否包含特定单词?

[英]How to check if a string contain specific words?

$a = 'how are you';
if (strpos($a,'are') !== false) {
    echo 'true';
}

In PHP, we can use the code above to check if a string contain specific words, but how can I do the same function in JavaScript/jQuery?在 PHP 中,我们可以使用上面的代码来检查一个字符串是否包含特定的单词,但是如何在 JavaScript/jQuery 中执行相同的功能呢?

you can use indexOf for this您可以为此使用 indexOf

var a = 'how are you';
if (a.indexOf('are') > -1) {
  return true;
} else {
  return false;
}

Edit : This is an old answer that keeps getting up votes every once in a while so I thought I should clarify that in the above code, the if clause is not required at all because the expression itself is a boolean.编辑:这是一个旧的答案,每隔一段时间就会投票一次,所以我想我应该澄清一下,在上面的代码中, if子句根本不需要,因为表达式本身是一个布尔值。 Here is a better version of it which you should use,这是您应该使用的更好版本,

var a = 'how are you';
return a.indexOf('are') > -1;

Update in ECMAScript2016: ECMAScript2016 中的更新:

var a = 'how are you';
return a.includes('are');  //true

indexOf / includes should not be used for finding whole words: indexOf / includes不应用于查找整个单词:

A word (in western culture) is a drawing of a symbols close to each other, with some space between each word.一个词(在西方文化中)是一个相互靠近的符号图,每个词之间有一些空间。 A word is considered as such if it's a complete piece of characters draw together and not a partial part of it:如果一个词是一个完整的字符组合在一起而不是它的一部分,那么它就被认为是这样的:

"has a word".indexOf('wor')  // 6 ("wor" is not a word in this sentence)
"has a word".includes('ha') // true ("ha" is not a word in this sentence)

Check if a single word ( whole word) is in the string检查字符串中是否有单个单词(整个单词)

Find a real whole word, not just if the letters of that word are somewhere in the string.找到一个真正的完整单词,而不仅仅是该单词的字母在字符串中的某个位置。

 const wordInString = (s, word) => new RegExp('\\b' + word + '\\b', 'i').test(s); // tests [ '', // true ' ', // true 'did', // true 'id', // flase 'yo ', // flase 'you', // true 'you not' // true ].forEach(q => console.log( wordInString('dID You, or did you NOt, gEt WHy?', q) )) console.log( wordInString('did you, or did you not, get why?', 'you') // true )

Check if all words are in the string检查是否所有单词都在字符串中

 var stringHasAll = (s, query) => // convert the query to array of "words" & checks EVERY item is contained in the string query.split(' ').every(q => new RegExp('\\b' + q + '\\b', 'i').test(s)); // tests [ '', // true ' ', // true 'aa', // true 'aa ', // true ' aa', // true 'd b', // false 'aaa', // false 'a b', // false 'aaaaa ', // false ].forEach(q => console.log( stringHasAll('aA bB cC dD', q) ))

If you are looking for exact words and don't want it to match things like "nightmare" (which is probably what you need), you can use a regex:如果您正在寻找确切的单词并且不希望它匹配诸如“噩梦”之类的东西(这可能是您需要的),您可以使用正则表达式:

/\bare\b/gi

\b = word boundary
g = global
i = case insensitive (if needed)

If you just want to find the characters "are", then use indexOf .如果您只想查找字符“are”,请使用indexOf

If you want to match arbitrary words, you have to programatically construct a RegExp (regular expression) object itself based on the word string and use test .如果要匹配任意单词,则必须基于单词字符串以编程方式构造一个 RegExp(正则表达式)对象本身并使用test

您正在寻找 indexOf 功能:

if (str.indexOf("are") >= 0){//Do stuff}

You might wanna use include method in JS.您可能想在 JS 中使用include方法。

var sentence = "This is my line";
console.log(sentence.includes("my"));
//returns true if substring is present.

PS: includes is case sensitive. PS:包括区分大小写。

An easy way to do it to use Regex match() method :-使用 Regex match() 方法的简单方法:-

For Example例如

var str ="Hi, Its stacks over flow and stackoverflow Rocks."

// It will check word from beginning to the end of the string

if(str.match(/(^|\W)stack($|\W)/)) {

        alert('Word Match');
}else {

        alert('Word not found');
}

Check the fiddle检查小提琴

NOTE: For adding case sensitiveness update the regex with /(^|\W)stack($|\W)/i注意:为了添加区分大小写,请使用/(^|\W)stack($|\W)/i更新正则表达式

Thanks谢谢

In javascript the includes() method can be used to determines whether a string contains particular word (or characters at specified position).在 javascript 中,includes() 方法可用于确定字符串是否包含特定单词(或指定位置的字符)。 Its case sensitive.它区分大小写。

var str = "Hello there."; 

var check1 = str.includes("there"); //true
var check2 = str.includes("There"); //false, the method is case sensitive
var check3 = str.includes("her");   //true
var check4 = str.includes("o",4);   //true, o is at position 4 (start at 0)
var check5 = str.includes("o",6);   //false o is not at position 6

This will这将

/\bword\b/.test("Thisword is not valid");

return false , when this one返回false ,当这个

/\bword\b/.test("This word is valid");

will return true .将返回true

 var str1 = "STACKOVERFLOW"; var str2 = "OVER"; if(str1.indexOf(str2) != -1){ console.log(str2 + " found"); }

Using a conditional ternary operator使用条件三元运算符

str = 'I am on StackOverflow';
str.match(/(^|\W)StackOverflow($|\W)/) ? 'Found. Why lie?' : 'Not Found';

If you'd like to find a single word in a string without regular expressions, you can do as follows:如果您想在没有正则表达式的字符串中查找单个单词,您可以执行以下操作:

function isWordInString(needle, haystack) {
  return haystack
    .split(' ')
    .some(p => (p === needle));
}
isWordInString('hello', 'hello great world!'); // true
isWordInString('eat', 'hello great world!'); // false

Advantages over regex:相对于正则表达式的优势:

  • Works with non-latin characters like Hebrew适用于非拉丁字符,如希伯来语
  • No need to sanitize the word you search in the string.无需清理您在字符串中搜索的单词。 Some methods in other answers will fail and return a false positive when searching for a "."搜索“。”时,其他答案中的某些方法将失败并返回误报。 (dot) (点)

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

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