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

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. 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

    ReplyDelete