2

I'm hoping someone can explain to me why I need to use "toLowerCase()" if I'm already using a regular expression that is case insensitive "i". The exercise is a pangram that can accept numbers and non-ascii characters, but all letters of the alphabet MUST be present in lower case, upper case, or mixed. I wasn't able to solve this exercise correctly until I added "toLowerCase()". This is one of the javascript exercises from exercism.io. Below is my code:

var Pangram = function (sentence) {
  this.sentence = sentence;
};

Pangram.prototype.isPangram = function (){
  var alphabet = "abcdefghijklmnopqrstuvwxyz", mustHave = /^[a-z]+$/gi, 
  x = this.sentence.toLowerCase(), isItValid = mustHave.test(x);

  for (var i = 0; i < alphabet.length; i++){
    if (x.indexOf(alphabet[i]) === -1 && isItValid === false){
      return false;
    }

  }
  return true;

};

module.exports = Pangram;
4

2 回答 2

2

正则表达式可能没有做你认为它正在做的事情。这是您对正在发生的事情进行评论的代码:

Pangram.prototype.isPangram = function (){
  var alphabet = "abcdefghijklmnopqrstuvwxyz", mustHave = /^[a-z]+$/gi, 
  x = this.sentence.toLowerCase(), isItValid = mustHave.test(x);

  // for every letter in the alphabet
  for (var i = 0; i < alphabet.length; i++){
    // check the following conditions:
    // letter exists in the sentence (case sensitive)
    // AND sentence contains at least one letter between a-z (start to finish, case insensitive)
    if (x.indexOf(alphabet[i]) === -1 && isItValid === false){
      return false;
    }

  }
  return true;

}

检查每个字母是否存在的逻辑与正则表达式无关,两者用于不同的目的。实际上,根据您对问题的描述,正则表达式在某些情况下会导致您的解决方案失败。例如,假设我们有字符串"abcdefghijklmnopqrstuvwxyz-"。在这种情况下,即使这句话应该返回 true,您的正则表达式也会测试为 false。

我的建议是删除正则表达式,toLowerCase在句子上使用,并遍历字母表,检查句子是否包含每个字母——这似乎是你所在的轨道。

以下是带有一些测试的示例解决方案。快乐学习!

function isPangram (str) {
  const alphabet = 'abcdefghijklmnopqrstuvwxyz'
  const strChars = new Set(str.toLowerCase().split(''))

  return alphabet.split('').every(char => strChars.has(char))
}

const tests = [
  "abc",
  "abcdefghijklmnopqrstuvwxyz",
  "abcdefghijklmnopqRstuvwxyz",
  "abcdefghijklmnopqRstuvwxyz-",
]

tests.forEach(test => {
  console.log(test, isPangram(test))
})

于 2017-12-11T03:58:06.907 回答
1

这是因为您正在手动检查小写字母:

if (x.indexOf(alphabet[i]) === -1)

alphabet[i]将是您定义为小写的字母字符串之一。

看起来你在这里根本不需要正则表达式,或者至少它没有做你认为它正在做的事情。由于您的正则表达式仅允许使用字母字符,因此如果您的句子有空格,它将失败。

于 2017-12-11T03:50:10.127 回答