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.
Asked
Active
Viewed 208 times
1 Answers
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
- 196,159
- 39
- 305
- 313
-
that's not replacing just the vowels :p - use `=> m.replace(/[aeiou]/gi, '*')` – Jaromanda X Oct 28 '20 at 23:14