JavaScript: Filter Bad Words in a String

In this post, we will see how to filter bad words in a string using JavaScript. To do so, we will first define an array that contains all the words that are to be filtered. We will then use a regular expression to check a piece of text (bad words) in a string.

Let us see some code:

title>JavaScript BadWord Filter by</title>
script type="text/javascript">
filterWords = ["fool", "dumb", "couch potato"];
// "i" is to ignore case and "g" for global
var rgx = new RegExp(filterWords.join(""), "gi");

function wordFilter(str) {
return str.replace(rgx, "****");

// call the function
document.write("Original String - ");
document.writeln("You fool. Why are you so dumb <br/>");
document.write("Replaced String - ");
document.writeln(wordFilter("You fool. Why are you so dumb"));

As you can see, the filterWords array contains some bad words we want to filter. We then use a Regex to match the pattern, as shown below.


The first parameter is a string with the pattern and the second patterns is to make the match case-insensitive and global (match more than one words)

The function wordFilter then uses this Regex to replace the abusive word with *****


That’s it. Call this function on a string and this is what you get.



See a Live Demo

About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.


Wy Sea said...
This comment has been removed by the author.
Wy Sea said...

How do i use this against a input textarea? to check example when a user type a bad word it auto convert into **** something like that?
it doesn't work in MVC 4? i tried not working