简体   繁体   中英

Filter out capitalized letters

For the code below, I'm trying to filter out the words 'bizz' and 'buzz' in this particular case some of these words are capitalized. WIthout adding these particular cases to the filtered word list can I remove these words so deBee just displays 'help'? Should also account for other cases where input string contains capital letters and doesn't alter those. eg "Help! buzz I'm buzz by buzz Bees!!" should return "Help! I'm by Bees!"

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!

You just need to compare lowercase values against each other.

 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!!")) 

I suggest using a Regular Expression

 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!!")) 

The below function will get the job done for you. Hopefully it helps :) I have added some comments to the code.

    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!!");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM