a swearword in javascript

You can use a regular expression and the replace() method to censor or remove swear words from a string in JavaScript. Here's an example:

index.tsx
const swearWords = /(fuck|shit|damn|asshole)/gi; // define swear words using a regular expression

const cleanString = (str) => {
  return str.replace(swearWords, "***"); // replace swear words with asterisks
}

const stringToClean = "What the f*ck did you just say, you little sh*t?";
console.log(cleanString(stringToClean)); // output: What the *** did you just say, you little ***
384 chars
9 lines

Alternatively, if you want to remove the swear words completely, you can use the filter() method to create a new array with all the words except the ones from a predefined list of swear words:

index.tsx
const swearWordsList = ["fuck", "shit", "damn", "asshole"]; // define a list of swear words

const cleanString = (str) => {
  const words = str.split(" "); // split the string into an array of words
  return words.filter(word => !swearWordsList.includes(word.toLowerCase())).join(" "); // return a new array with all the non-swear words joined back into a string
}

const stringToClean = "What the fuck did you just say, you little shit?";
console.log(cleanString(stringToClean)); // output: What the did you just say, you little?
531 chars
10 lines

gistlibby LogSnag