使用数组中的所有字符串匹配字符串

match a string using all the strings in array

本文关键字:字符串 字符 串匹配 数组      更新时间:2023-09-26

你好,我正在尝试用javascript制作一个简单的匹配游戏。

如果用户以包含word_tmp中每个字符串的任何方式插入文本president goes crazy,则word_tmp变为true,如果他错过了一个字符串,则变为false。

word_tmp = ['president', 'goes', 'crazy'];
// string 1 contains the president, goes and crazy at one string
string1 = 'president goes very crazy'; // should output true
// string 2 doesn't contain president so its false.
string2 = 'other people goes crazy'; // should output false

我怎样才能做到这一点?

试试这个:

var word_tmp = ['president', 'goes', 'crazy'];
var string1 = 'president goes very crazy';
var isMatch = true;
for(var i = 0; i < word_tmp.length; i++){
    if (string1.indexOf(word_tmp[i]) == -1){
        isMatch = false;
        break;
    }
}
return isMatch //will be true in this case

您可以使用简单的reduce调用:

word_tmp.reduce(function(res, pattern) {
  return res && string1.indexOf(pattern) > -1;
}, true);

相同的代码,封装在一个函数中:

var match_all = function(str, arr) {
  return arr.reduce(function(res, pattern) {
    return res && str.indexOf(pattern) > -1;
  }, true);
};
match_all(string1, word_tmp); // true
match_all(string2, word_tmp); // false

但如果你想匹配整个单词,这个解决方案就不适用了。我的意思是,它将接受像presidential elections goes crazy这样的字符串,因为president是单词presidential的一部分。如果你也想消除这样的字符串,你应该首先拆分你的原始字符串:

var match_all = function(str, arr) {
  var parts = str.split(/'s/); // split on whitespaces
  return arr.reduce(function(res, pattern) {
    return res && parts.indexOf(pattern) > -1;
  }, true);
};
match_all('presidential elections goes crazy', word_tmp); // false

在我的示例中,我在空白/'s/上拆分原始字符串。如果你允许标点符号,那么最好在非单词字符/'W/上拆分。

var word_tmp = ['president', 'goes', 'crazy'];
var str = "president goes very crazy"
var origninaldata = str.split(" ")
var isMatch = false;
for(var i=0;i<word_tmp.length;i++) {
   for(var j=0;j<origninaldata.length;j++) {
      if(word_tmp[i]==origninaldata[j])
        isMatch = true;
   }
}