Detect if particular word typed in textarea in JavaScript

In this post, we are going to see how to detect if particular word typed in textarea in JavaScript.

Often one may need to prevent textarea from some forbidden word in the project. So in that case, it needs to check if that forbidden word typed in the textarea or not and depending upon that show the warning message to the user.

Here we are going to detect when the forbidden word typed in textarea or not and depending upon that we are going to show the warning message. All these tasks will be done on the client side to improve the user experience.

Let’s first create our HTML textarea with a blank paragraph with its Ids:

<p id="warning_text" style="color: red;"></p>
<textarea id="myText" rows="8" cols="55"></textarea>

The paragraph tag above the text area will show the warning message when our particular word is typed in textarea.

Below is the JavaScript code that will show the warning message when a specific word type:

document.getElementById('myText').onkeyup = function(){
  
   var text_value = document.getElementById('myText').value;
   
   if (text_value.includes("word") === true) {
   	document.getElementById('warning_text').innerHTML = "You are using the forbidden word";
   } else {
   	document.getElementById('warning_text').innerHTML = "";
   }

};

In the above code, we have used the onkeyup event listener so that we can check for the specific word everytime we type in the text box.

Also, read:

 

Inside the event listener, we have used the JavaScript string includes() method. We are using this method to find out if that particular word exists or not in the text box. The includes() method determines whether a string contains the characters of a specified string.

To show the warning message above the text inside the paragraph text we have applied HTML DOM innerHTML property. The innerHTML property can put any HTML content inside an element.

Now you can run the code on your browser. When you start typing in the text box and it contains “word”, then it will show the warning message inside the paragraph. The warning message that will show is “You are using the forbidden word”. Of course, you can use your own message.

If you remove the forbidden word from the textarea, then the warning message will be removed. This is because we have set the innerHTML blank in if else condition when the word doesn’t exist.

 

One response to “Detect if particular word typed in textarea in JavaScript”

  1. Sea says:

    How would you add multiple words to be detected? I tried-
    if (text_value.includes(“word”, “secondword”) === true)

    but no luck.

Leave a Reply

Your email address will not be published. Required fields are marked *