Detect first person writing with time interval in Javascript

Viewed 65

I'm looking for a way to detect writing in the first person when a user types "We", "us", "our" and a couple more pronouns, but not using the keyup event directly but with an interval of five seconds as they type in a textarea or text field.

I've tried the keyup event but I'm unable to detect and parse the pronouns to display a warning div that shows if the field contains these pronouns or text.

2 Answers

Add an input event listener on the textarea and using setTimeout(), add the timeout of 5 seconds. Before calling setTimeout(), check if there's any timeout already set. If there is, clear that timer and add a new one.

To check for the particular words within the textarea, use a regular expression.

const textarea = document.querySelector('textarea');
const regex = /\b(?:we|us|our)\b/gi;
let timerID;

textarea.addEventListener('input', (event) => {
  if (timerID) {
    clearTimeout(timerID);
  }

  timerID = setTimeout(() => {
    if (regex.test(textarea.value)) {
      console.log('warning...');
    }

  }, 5000);
});
<textarea></textarea>

You could use a regex pattern, here is an example

const element = document.getElementById('element');
warn=document.getElementById("warning")
pattern=/\b(we|us|our)\b/g
element.addEventListener("input",function(){
 if(pattern.test(this.value)){
  warn.textContent="Warning"
 }
  else return 
})
<input id="element" type="text">
<div id="warning"></div>

Related