遍历字符串并删除所有实例

Iteration through string and remove all instances of

我的指示是遍历一个字符串并删除字母 "a" 的所有实例。我以为很容易找到例子,但我做不到。有些人会在没有迭代的情况下删除字母,但这不是说明所要求的。如果有人可以查看我的代码并协助我完成任务,我将不胜感激! "removeA" 函数现在将遍历字符串,并且只有控制台记录 !== "a",但对于我来说,我无法弄清楚如何将它保存到新字符串中。提前致谢。

removeA = function(stringWithA) {
    if (stringWithA === null || typeof (stringWithA) !== "string" || stringWithA === "") {  //Checking for is null AND is not array
        return 'Please enter a valid string';
    } else {
        lowerWithA = stringWithA.toLowerCase();
        for (var i = 0; i < lowerWithA.length; i++) {
            if (lowerWithA.charAt(i) !== "a") {
                console.log(lowerWithA.charAt(i));
            }
        }
    }
}

您可以将字母存储到数组中。

var removeA = function(stringWithA) {

  if (stringWithA === null || typeof(stringWithA) !== "string" || stringWithA === "") { //Checking for is null AND is not array
    return 'Please enter a valid string';
  } else {
    var newString = [];
    lowerWithA = stringWithA.toLowerCase();
    for (var i = 0; i < lowerWithA.length; i++) {
      if (lowerWithA.charAt(i) !== "a") {
        newString.push(lowerWithA.charAt(i))
      }
    }
    
    return newString.join('');
  }
}

console.log(removeA("Eleazar"))

或者,只需使用 regex:

var removeA = function(stringWithA) {
  if (stringWithA === null || typeof(stringWithA) !== "string" || stringWithA === "") { //Checking for is null AND is not array
    return 'Please enter a valid string';
  } else {
    return stringWithA.replace(/a/gi, '')
  }
}

console.log(removeA("EleaaaaazAreeeeaaaElAAAAAeaaaEleEvene"))

为什么不使用所有不是 a 的字符构建一个新字符串?

var newString = "";

for (var i = 0; i < lowerWithA.length; i++) {
    var letter = lowerWithA.charAt(i);
    if (letter !== "a") {
        newString += letter;
    }
}

console.log(newString);

如果您想将其扩展为 case-insensitive:

...
if (letter !== 'a' || letter !== 'A') { ... }

并且不要在原始字符串上调用 String.toLowerCase()

我想你需要的功能已经有了,replace:

var stringWithA = 'A aaaa bbbcc!';
alert(stringWithA.replace(/[Aa]/g, ''));