Stop users from inputting particular words into a <textarea> box

I recently watched a tutorial on YouTube by the developphp guy and learned how to prevent people from inputting inappropriate words in my form's text area.

However, I want to block multiple words instead of just one, but the tutorial didn't cover that. I've been trying to find a solution without success. Can someone please help me?

Here is the current JavaScript code:

HTML

<textarea class="ta" id="ta" name="ta" onkeyup="clean('ta')" onkeydown="clean('ta')" placeholder="Enter a positive message"></textarea>

JAVASCRIPT

<script type="text/javascript">
        function clean(el){
var textfield = document.getElementById(el);
var regex = /badword1|badword2/gi;
if(textfield.value.search(regex) > -1) {
    textfield.value = textfield.value.replace(regex, "");
    }
}
</script>

Thank you for your assistance!

Answer №1

Constructing your regular expression using | (pipe) to separate words is an effective way:

textfield.value = textfield.value.replace(/badword1|badword2|badwordn/gi , "" );

Answer №2

If you're looking for a simple solution, using a library like jQuery to monitor key presses in a text box might be the way to go.

<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>

<textarea id="mytextArea" style="width:200px; height:300px"></textarea>

$(document).ready(function() {
  $('#mytextArea').keyup(function() {
    var textBoxValue = $(this).val();
    console.log(textBoxValue);

    var forbiddenWords = [
      'explicative1',
      'explicative2'
    ];

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

    $(this).val(textBoxValue);
  });
});

Give it a try over at https://jsfiddle.net/t1p27hv4/

Keep in mind that there may still be cases like 'f uck' where the forbidden array wouldn't catch them, so using regex could offer a more thorough approach. Feel free to explore that option and remember, someone may have already tackled this issue before, so a quick search might yield some helpful results.

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

Execute various settimeout or display functions on various elements of a webpage

Just a heads up, I'm not really experienced in development. More on the newbie side of things, but eager to learn. I've been looking for an answer to my question, but so far haven't come across anything that fits my specific situation. It m ...

press a cURL PHP ajax button to trigger an action

Hello everyone, I could really use some help here. I've been looking at similar questions but none of the answers seem to apply to my situation. I extracted a page using curl, however, there's a button on that page that I am unable to interact w ...

Issue with React.js button functionality not functioning as expected

import React, { Component } from 'react'; import './App.css'; class App extends Component { constructor(props) { super(props); this.state = { items: [] } } addItem(e) { var itemArray = this.state.items; ...

Transforming intricate JavaScript objects into JSON format using Node.js

Currently, I am engaged in a web scraping project and my goal is to construct a JSON object from the gathered data. Below is an outline of the steps I am taking to achieve this: var submitButton = driver.findElement(By.className('btn btn-primary& ...

Encountering an issue with the ts.createNodeArray function during the compilation of a NestJS project

Our NestJS project recently underwent a migration from node v14 to node v19.7, necessitating an update of all packages in the package.json file. However, this update has led to a strange error that we are currently struggling to identify and resolve. Her ...

Looking for assistance in transferring information from one webpage to another dynamic webpage

I'm in the process of building a website to feature products using NextJs. My goal is to transfer data from one page to another dynamic page. The data I am working with consists of a json array of objects stored in a data folder within the project. Wh ...

Having trouble locating an element on a webpage? When inspecting the element, are you noticing that the HTML code differs from the source page?

I'm having trouble locating a specific element on a webpage. When I use the Inspect Element tool, I can see the HTML code with the element id = username, but when I check the page source, all I see is JavaScript code. Does anyone have any suggestions ...

Updating Object Properties in Vue.js 2.0 using Methods

I am facing an issue where I have an object with blank properties in my component's data. I want to update these properties using a method that is triggered by a click event on one of the listed elements. However, when I check the click event in the c ...

Does AngularJS have a similar function to $(document).ajaxSuccess()?

When working with AngularJS, I am looking to implement a universal ajax loader that does not require integration into each controller to function. In jQuery, this can be achieved through the following code: (function globalAjaxLoader($){ "use strict"; ...

What is the best way to change the class of the inline table of contents element using JavaScript?

INQUIRY Hello, I am currently working on building a straightforward navigation site and I have a question regarding how to modify or add a class to one of the li elements within the inline table of contents (toc) on the right side. I want to style it usin ...

Issue with implementing MUI Style Tag in conjunction with styled-components and Typescript

I have created a custom SelectType component using Styled Components, which looks like this: import Select from '@mui/material/Select'; export const SelectType = styled(Select)` width:100%; border:2px solid #eaeaef; border-radius:8px ...

The AngularJS Factory $http encounters an error when attempting to read the property 'length' of an undefined value

I am looking to implement a factory in my REST Controller that will return an array of Strings. I want to be able to reuse this function in my services.js file. Here is the HTML for an Autocomplete input field: <input type="text" ng-model="vertrag.ver ...

What could be the reason for StaticComponent constantly re-rendering despite having a static state that does not change

I'm trying to grasp the core concepts of how React triggers component re-rendering upon state changes. In the scenario described below, the console.log('hi') statement within the StaticComponent is executed every time the onChange event han ...

Updating the title with respect to the current route in AngularJS 1

Is it possible to dynamically change the title displayed in a header based on the current route provided by the router, even when outside of the controller scope? For example, I have a mainMenu controller that is loaded when a specific route is called. The ...

Tips on how to rewind a glTF animation in Three.js if it does not intersect with an object

I have been experimenting with incorporating a gltf model into a three js project and I'm wondering if there's a way to reverse a gltf animation when the mouse moves away from the model. Currently, I've managed to trigger the animation as th ...

Is it possible to utilize ag-grid's API to filter multiple checkbox values simultaneously?

I am currently utilizing angularjs and have implemented a series of checkboxes to filter my ag-grid. So far, I have successfully utilized radio buttons and the api.setQuickFilter method for filtering based on individual values. However, I am facing an iss ...

Run JavaScript code to retrieve the console log using Selenium WebDriver or WatiN

(Apologies for the detailed explanation) I am looking to ensure a page loads entirely before proceeding, but it seems browsers have varied responses when attempting to use readyState or onLoad. In the application I am currently developing, a specific l ...

Could you assist me in obtaining $randomQ and $matchinA, and then triggering a jQuery refresh when $matchinA is entered?

Could someone kindly assist me with retrieving a random question, labeled as '$randomQuestion' (e.g., "What color is the sky?"), along with its corresponding answer, $matchingAnswer, from the quizID section of my SQL database? I would also like t ...

Issue with Google Charts where the label does not show outside of the bar if the bar is too small

I am encountering an issue with my Google Bar Chart where the bar label is not displaying outside of the bar when it is too large to fit inside. This behavior should be the default, but my charts are not working as expected. The problem can be seen in rows ...

Encountering a 403 Forbidden error when attempting to include a full URL in my JSON data using jQuery and PHP

I am currently working on a project to create a card generator for educational purposes and to have some fun. I am learning how to gather data from user inputs and save it to a database. However, I encountered an issue when trying to send a simple JSON da ...