-2

I am making a filter to block bad words and I am looking for a way to search a block of text for a word then replace the vowels of that word with * Is there a way to do this with a regex expression.

Tyler
  • 37
  • 7

1 Answers1

1

Using String.prototype.replace()

You could .join("|") an Array of bad words into a string like bad|awful|sick where the pipe | will act as a RegExp list of alternatives.

const text = "This is nice and I really like it so much!";
const bad = ["much", "like", "nice"].join("|");
const fixed = text.replace(new RegExp(`\\b(${bad})\\b`, "ig"), m => m.replace(/[aeiou]/ig, "*"));

console.log(fixed);

To replace the entire word with * use:

text.replace(new RegExp(`\\b(${bad})\\b`, "ig"), m => "*".repeat(m.length));

If you want to also target compound words (i.e: unlike given like is a bad word) than use simply RegExp(bad, "ig") without the \b Word Boundary assertion.

Also, if necessary escape your bad words if some contain RegExp special characters like . etc...

Roko C. Buljan
  • 164,703
  • 32
  • 260
  • 278