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:

<head>
<
title>JavaScript BadWord Filter by DevCurry.com</title>
<
script type="text/javascript">
var
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"));
</script>
</
head>

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.

image

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 *****

image

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

OUTPUT

image

See a Live Demo



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

2 comments:

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