过滤掉大写字母

时间:2018-12-10 21:28:15

标签: javascript

对于下面的代码,在这种特殊情况下,我试图过滤出“ bizz”和“ buzz”两个词,其中一些词用大写字母表示。如果不将这些特殊情况添加到过滤的单词列表中,是否可以删除这些单词,以便deBee仅显示“帮助”? 还应该考虑输入字符串包含大写字母且不会更改大写字母的其他情况。 例如“帮助!嗡嗡声,我被嗡嗡声的蜜蜂嗡嗡声!!”应该返回“帮助!我在蜜蜂身边!”

function deBee(str) {
  const filtered = ['bizz', 'buzz']
  return str.split(' ').filter(i = > !filtered.includes(i)).join(' ')
}
deBee("Buzz BUzz BuZZ help BUZZ buzz")
deBee("Help! buzz I'm buzz buzz surrounded buzz by buzz buzz Bees!!")
//Should return "Help! I'm surrounded by Bees!

3 个答案:

答案 0 :(得分:1)

您只需要相互比较小写字母值。

function deBee(str) {
  const filtered = ['bizz', 'buzz']
  return str.split(' ').filter(i => !filtered.includes(i.toLowerCase())).join(' ')
}

console.log(deBee("Buzz BUzz BuZZ help BUZZ buzz"))
console.log(deBee("Help! buzz I'm buzz by buzz Bees!!"))
console.log(deBee("Help! buzz I'm buzz buzz surrounded buzz by buzz buzz Bees!!"))

答案 1 :(得分:0)

我建议使用正则表达式

const deBee = str => str
  .split(' ')
  .filter(word => !/^b[iu]zz$/i.test(word))
  .join(' ');

console.log(deBee("Buzz BUzz BuZZ help BUZZ buzz"))
console.log(deBee("Help! buzz I'm buzz buzz surrounded buzz by buzz buzz Bees!!"))

答案 2 :(得分:0)

以下功能将为您完成工作。希望它会有所帮助:) 我已经在代码中添加了一些注释。

    const deBee = str => {
    // Turn the string into an array because it is easier to work with arrays.
    str = str.split(" ");
    // cleanArr will be used to store the new string
    var cleanArr = [];
    for(var char in str){
        // Remove special chars and make all the words lower case
        if(str[char].replace(/[^\w]/g, '').toLowerCase() !== 'buzz'){
            cleanArr.push(str[char]);
        }
    }
    console.log(cleanArr.join(" "));
}
deBee("Buzz BUzz BuZZ help BUZZ buzz")
deBee("Help! buzz I'm buzz buzz surrounded buzz by buzz buzz Bees!!");