JavaScript simple profanity filter

Viewed 4694

Hi I want to create very basic profanity filter in JavaScript.

I've an array called badWords and also I've constant called description. I won't to check whether there is any bad word contains in that description.

This is what I've done upto now.

const badWords = ["Donald Trump","Mr.Burns","Sathan"];

const description = "Mr.Burns entered to the hall."
let isInclude = false;
badWords.forEach(word=>{
  if(description.includes(word)){
  isInclude = true
  }
})

console.log(`Is include`,isInclude)

Only problem is I've to loop through badWords array. Is there a way to get this done without looping through the array?

3 Answers

Use some() - it exits from the loop as soon as a match to the condition is found, as such it's more performant than a loop.

let isInclude = badWords.some(word => description.includes(word));

Here's what the regexp solution looks like:

// https://stackoverflow.com/a/3561711/240443
const reEscape = s => s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');

// needs to be done only once
const badWords = ["Donald Trump","Mr.Burns","Sathan"];
const badWordsRE = new RegExp(badWords.map(reEscape).join('|'));

// testing is quick and easy
console.log("Mr.Burns entered to the hall.".match(badWordsRE)); // "Mr.Burns"
console.log("Nothing objectionable".match(badWordsRE));         // null

(If your bad words are actual regexps, like "Mr\.Burns", then leave out the .map(reEscape))

use try catch

const badWords = ['Donald Trump', 'Mr.Burns', 'Sathan']

const description = 'Mr.Burns entered to the hall.'
let isInclude = false
try {
  badWords.forEach(word => {
    if (description.includes(word)) {
      isInclude = true
      throw new Error(word)
    }
  })
} catch (e) {
  console.log(e)
}
Related