Is there a way to eliminate a certain word from being used?

My goal is to mask inappropriate words with asterisks ***. However, I've encountered a challenge when the offensive word is part of another word that shouldn't be replaced.

for(var i = 0; i < forbidden.length; i++) {
    if(textBoxValue.search(forbidden[i]) > -1) {
        textBoxValue = textBoxValue.replace(forbidden[i], '');
    }
}

For instance, if the unacceptable word is "are", and it appears within another word like "aren't", I do not want it to display as "***n't". The replacement should only occur if the word stands alone.

Answer №1

To ensure that a matched word is standalone, one option is to use a regular expression with a word boundary on each side:

forbidden.forEach((word) => {
  textBoxValue = textBoxValue.replace(new RegExp('\\b' + word + '\\b', 'g'), '');
});

For instance:

let textBoxValue = 'bigwordfoo foo bar barbaz';
const forbidden = ['foo', 'bar'];

forbidden.forEach((word) => {
  textBoxValue = textBoxValue.replace(new RegExp('\\b' + word + '\\b', 'g'), '');
});
console.log(textBoxValue);

If the intention is to replace with asterisks instead of an empty string, a replacer function can be used:

let textBoxValue = 'bigwordfoo foo bar barbaz';
const forbidden = ['foo', 'bar'];

forbidden.forEach((word) => {
  textBoxValue = textBoxValue.replace(
    new RegExp('\\b' + word + '\\b', 'g'),
    word => '*'.repeat(word.length)
  );
});
console.log(textBoxValue);

It's worth noting that word restrictions can often be bypassed by determined individuals. Humans are usually able to find ways to outsmart heuristics.

If any of the blacklisted words contain special characters in a regular expression, it is recommended to escape them first before passing them to new RegExp:

const escape = s => s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');

let textBoxValue = 'bigwordfoo foo ba$r ba$rbaz';
const forbidden = ['foo', 'ba$r'];

forbidden.forEach((word) => {
  textBoxValue = textBoxValue.replace(
    new RegExp('\\b' + escape(word) + '\\b', 'g'),
    word => '*'.repeat(word.length)
  );
});
console.log(textBoxValue);

Answer №2

To create a dynamic regex that includes all the forbidden words separated by a | for an alternation effect, you can surround it with word boundaries (\b) to ensure only full word matches are replaced.

For instance, if the forbidden words are 'bad', 'nasty', and 'dreadful', the resulting dynamic regex would be:

/\b(?:bad|nasty|dreadful)\b/g

In the second parameter of the replace function, the matched word is passed as a parameter. By utilizing the repeat method, you can replace the word with * characters repeated the same number of times as the length of the word to be replaced.

function replaceBadWords(textBoxValue, forbidden) {
  const regex = new RegExp(`\\b(?:${forbidden.join('|')})\\b`, 'g')
  return textBoxValue.replace(regex, m => "*".repeat(m.length))
}

const forbidden = ['bad', 'nasty', 'dreadful']

console.log(replaceBadWords('string with some nasty words in it', forbidden))
console.log(replaceBadWords("bad gets replaced with asterisks but badminton won't", forbidden))

Answer №3

Have you considered utilizing a library for filtering out inappropriate language? If not, or if you're looking for one to use, check out this repository.

This library already contains a comprehensive list of bad words, saving you the trouble of compiling your own list and potentially missing some.

One useful feature is the ability to use placeholders, such as:

var Filter = require('bad-words');
var customFilter = new Filter({ placeHolder: 'x'});

customFilter.clean('Don't be an ash0le'); //Don't be an xxxxxx

You can also customize the library by adding or removing your own set of bad words:

var filter = new Filter(); 

// add to list
filter.addWords('some', 'bad', 'word');

// remove from list
filter.removeWords('hells', 'sadist');

Additionally, the library offers multilingual support if you provide the appropriate regex patterns.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I'm having trouble understanding why my data does not appear even though there is space allocated for it automatically

I'm facing an issue with my code that is supposed to populate a table with dynamic content using react and ant.design. Everything seems to be working fine, but the actual content is not displaying - only the space for it is created. What's happe ...

Refreshing a Web Page with JavaScript

I'm currently facing an issue with my Rails application that includes JavaScript. The JavaScript works fine when the document is initially loaded, but I need it to reload whenever a new page is visited. Is there a way to achieve this without having to ...

What are the best methods for cropping SVG images effectively?

Is it possible to crop a large SVG background that has elements rendered on top of it so that it fits the foreground elements? I am using svg.js but have not been able to find a built-in function for this. Can an SVG be cropped in this way? ...

Expanding Input Options Based on Dropdown Selections (PHP and JavaScript)

I am looking to dynamically add new input fields based on the option value selected from a dropdown menu. Here is an example of what the dropdown looks like: <form action="#" method="post"> <select name="job" id=& ...

The updated positions of vertices in three.js geometry after they have been moved

I am new to 3D manipulation and learning about Three.js. One thing I'm struggling with is understanding how to retrieve the updated vertex coordinates after moving a geometry. The code I've written below seems to only return the original coordina ...

Experiencing CORS issue on the frontend while using Django backend

I am currently accessing a Django REST POST API http://127.0.0.1:8000/api from my frontend located at http://127.0.0.1:5500/index.html. I have set up django-cors-headers and ensured that the frontend's image_upload.js, backend's settings.py, view ...

Is the input field not properly centered on the page?

Can someone explain why the input field is not aligning in the center? I am new to web development and need some assistance. <input type="text" id="search_bar" class="form-control" placeholder="Search" align="center"> In my CSS, I've ...

Next step is to retrieve previous store information

As a newcomer to the world of Javascript and Reactjs, I encountered an issue while attempting to execute multiple actions upon clicking a button. The first action successfully updates the store data, however, the second action seems to be using the old sto ...

Create a JavaScript function without attaching it to the global window object

Can someone please help me with defining a function and using it inside Jquery within the $(document).ready block? function addLeadingZero(number) { return (number < 10 ? '0' : '') + number } I'm not confident that I ha ...

Filtering data in an antd table by searching

Just starting out with React hooks, specifically using TypeScript, and I'm struggling to implement a search filter with two parameters. Currently, the search filter is only working with one parameter which is 'receiver?.name?'. However, I wo ...

Verifying email addresses through JavaScript and an activation process

I am in the process of implementing email confirmation/verification for my Login & Registration feature. I came across Activator on github, which claims to be a straightforward solution for managing user activation and password reset in nodejs apps (http ...

Searching for object in array using NodeJS with specific key value

Is there a way to retrieve an object from an array based on the value of one of its keys? Consider the following array: var arr = [ { city: 'Amsterdam', title: 'This is Amsterdam!' }, { ...

Execute function when button is clicked in ExpressJS

I am looking to execute a function on my node server when a button on my website is clicked: What I currently have: Index.html (I have not included the entire content for simplicity) <button id="tv">tv</button> Client.js (Client side) const ...

The JavaScript code fails to run after implementing highway.js unless the page is manually refreshed

Recently I started using highway.js to implement a fade out/fade in effect while navigating between pages. Despite going through the documentation, I couldn't figure out why my other JavaScript files aren't activating when the new content block l ...

Code with Javascript using Selenium and WebdriverIO framework

When conducting tests, my directory structure is set up as follows: custom lib tests pages Each JavaScript function that is written in the 'custom' directory can be accessed by the 'test' directory through a "browser ...

Time taken to execute all the tests using the karma runner

We have recently transitioned to running unit tests remotely using browserstack across multiple browsers and operating systems with the help of the karma-browserstack-launcher plugin. The current output of our test run appears as follows: $ grunt unit:re ...

A platform for creating ER and flow diagrams specifically tailored for web applications, utilizing open source software

Our team is currently working on creating a web application that enables users to create diagrams, such as flow or ER diagrams. We are looking for ways to convert these diagrams into XML or other formats for representation. Are there any open-source soft ...

isolated scope custom directive for showcasing multiple image slideshows

The concern I am looking to integrate this image carousel in multiple locations on the same page using the same directive. However, it appears that they are currently sharing the same scope. For example: When I click the arrow icons to navigate to the n ...

Embarking on the journey of launching an Angular application on AWS CloudFront

I have a Laravel PHP application that functions as an API accessed by an Angular single-page app. Currently, the Angular app is situated within the public folder, but I aim to separate it so I can deploy it through Amazon CloudFront. I came across this ar ...

Fetching Highcharts information through ajax results in the removal of Datalabels

I have a HighCharts bar chart that is updated with data from an ajax call as shown below. var updateChart = function() { $.ajax({ url: "/theurl/theid", type: "Get", success: function(data) { ...