Text-processing : Bad words filter in JavaScript

Vipasha Vaghela
2 min readFeb 4, 2021

Introduction

As social media is getting popular day by day, so the trend of using bad words in comments or posts also increases day by day. by saying these words, people are bullying their peers which is ok to some extent. But when it comes to cyberbullying, it affects a lot to the other peer and Sometimes such things can lead to depression. So we have to stop this in order to not encourage that.

As being Software developer we can provide some facilities in software like bad-word detection, bad-word filter or automatic spam detection in order to reduce this problem. So in this article we are going to see how to create a bad-word filter in javaScript.

There are many libraries in javascript to detect bad-words but, here we are going to use npm library “bad-words” to create our filter. Here nodejs is used to execute code, you can use this package in vanilla javascript or any other frameworks also.

Link to “Bad-words” package

bad-words — npm (npmjs.com)

Here we are using nodejs to execute our code.

first we have to install package.

npm install bad-words

Example 1:

//first Import package and assign to a variable

var Filter = require(‘bad-words’),

filter = new Filter();

// Initializes a new filter object

var customFilter = new Filter({ placeHolder: ‘x’});

// here we will assign a placeholder pattern as “x” we can put “*” also

customFilter.clean(“Don’t be an ash0le”)

// here clean function automatically detect bad words and replace this text with placeholder “*”

console.log(filter.clean(“Don’t be an ash0le”));

//It will print output on console .

// output :: Don’t be an ******

var Filter = require('bad-words'),filter = new Filter();console.log(filter.clean("Don't be an ash0le")); 
//Don't be an ******

Example 2 :

Regex Overrides

var filter = new Filter({ regex: /\*|\.|$/gi });var filter = new Filter({ replaceRegex:  /[A-Za-z0-9가-힣_]/g });//multilingual support for word filtering

Example 3 :

Remove words from Predefine custom array

let filter = new Filter();filter.removeWords('hells', 'sadist');filter.clean("some hells word!"); //or use an array using the spread operatorlet removeWords = ['hells', 'sadist'];filter.removeWords(...removeWords);filter.clean("some sadist hells word!");

Conclusion

Don’t give hurtful words to others on any platform and don't offend anyone.

Link of github, where I have attached examples of text processing in JavaScript : https://github.com/vipashaaV321/NLP_Processing-BadWordFilter.

--

--