match a string using all the strings in array
你好,我正在尝试用javascript制作一个简单的匹配游戏。
如果用户以任何方式插入文本
1 2 3 4 5 6 7 | 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 |
我怎样才能做到这一点?
您可以使用简单的reduce call:
1 2 3 | word_tmp.reduce(function(res, pattern) { return res && string1.indexOf(pattern) > -1; }, true); |
用函数包装的相同代码:
1 2 3 4 5 6 7 8 | 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 |
但如果你想匹配整个单词,这个解决方案就不适用了。我的意思是,它会接受像
1 2 3 4 5 6 7 8 | 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 |
在我的示例中,我将在空白处分解原始字符串
试试这个:
1 2 3 4 5 6 7 8 9 10 11 12 | 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 |
1 2 3 4 5 6 7 8 9 10 11 | 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; } } |