我尝试检查一个单词(wordToCheck
)是否只包含数组中的字母(letters
),并且只包含数组中的每个字母(或者更确切地说不是它们的次数)在数组中)因为它实际上在数组内部。
以下是所需功能应返回的示例:
checkIfWordContainsLetters("google", ["a","o","o","g","g","l","e","x"]) === true
checkIfWordContainsLetters("google", ["a","o","g","g","l","e","x"]) === false
如何使此代码有效?
function checkIfWordContainsLetters(wordToCheck, letters) {
var lettersToString = letters.toString();
var lettersTrimmed = lettersToString.replace(/,/gi, "?");
var regEx = new RegExp(lettersTrimmed, "gi");
if (wordToCheck.match(regEx)!== null) {
return true;
}
else return false;
}
答案 0 :(得分:3)
您可以使用此ES6功能:
function checkIfWordContainsLetters(wordToCheck, letters){
return !letters.reduce((a, b) => a.replace(b,''), wordToCheck.toLowerCase()).length;
}
console.log(checkIfWordContainsLetters("google", ["a","o","o","g","g","l","e","x"]));
console.log(checkIfWordContainsLetters("google", ["a","o","g","g","l","e","x"]));

我的想法是浏览 letters 数组中的每个字母,并在给定的 wordToCheck 参数中删除一个(不是更多!)的字母(好吧,不是完全 in 它,但是拿一个缺少那一个字符的副本)。如果在进行这些删除后仍有剩余字符,则返回值为false
- true
。
当然,如果您使用Internet Explorer,您将无法获得必要的ES6支持。这是与ES5兼容的代码:
function checkIfWordContainsLetters(wordToCheck, letters){
return !letters.reduce(function (a, b) {
return a.replace(b, '');
}, wordToCheck.toLowerCase()).length;
}
console.log(checkIfWordContainsLetters("google", ["a","o","o","g","g","l","e","x"]));
console.log(checkIfWordContainsLetters("google", ["a","o","g","g","l","e","x"]));

答案 1 :(得分:1)
只要它不是长字符串的最佳解决方案,使用一些聪明的正则表达式肯定更好,它适用于没有空格的短字符串。
function checkIfWordContainsLetters(word, letters){
word = word.toLowerCase().split('');
for(var i = 0; i < letters.length; i++) {
var index = word.indexOf( letters[i].toLowerCase() );
if( index !== -1 ) {
// if word contains that letter, remove it
word.splice( index , 1 );
// if words length is 0, return true
if( !word.length ) return true;
}
}
return false;
}
checkIfWordContainsLetters("google", ["a","o","o","g","g","l","e","x"]); // returns true
checkIfWordContainsLetters("google", ["a","o","g","g","l","e","x"]); // returns false