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

问题描述

我需要比较jQuery中字符串中的单词.简而言之,字符串中的每个单词都应为true,否则为true.顺序无关紧要.

I need to compare the word from the string in jQuery. In short each word is in the string then match should be true, otherwise not. It doesn't matter what sequence.

例如,如果我有这样的句子:I need to Visit W3Schools

For example if I have the sentence: I need to Visit W3Schools

如果我搜索need w3school ==>匹配
如果我搜索need go w3school ==>不匹配
如果我搜索w3schools visit ==>匹配
如果我搜索need go ==>不匹配

If I search need w3school ==> Match
If I search need go w3school ==> Not Match
If I search w3schools visit ==> Match
If I search need go ==> Not Match

可以是多个单词,例如1、2或大于2.

It can be multiple words like 1, 2 or more than 2.

我用过

var keyword = "I need to Visit W3Schools";

if(keyword.indexOf('need w3school') != -1){
   console.log('Found');
}else{
    console.log('Not Found');
}

但是它仅在后续单词中起作用,而在其他情况下"w3schools visit"则无效.

But it works only subsequent word not other case "w3schools visit".

推荐答案

//Function CheckForWords accepts the text value
//Splits text value on whitespace, iterates each word,
//Checks if each word is found in text, if not returns false
function CheckForWords(text){
   const words = text.split(' ');

   for(let x = 0; x < words.length; x++){
        if(text.toLowerCase().indexOf(words[x].toLowerCase()) === -1){
            return false;
        }
   }

   return true;
}

这篇关于在javascript中包含整个字符串中的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 15:50