Home > Back-end >  JS - Parse each word and not a string pattern
JS - Parse each word and not a string pattern

Time:07-19

Im coding a discord.js bot to prevent from displaying message with banned words into. I have an array containing all the banned words and Im checking if the message contain one of them with .includes method.

My issue is that this method parse the whole string pattern so let's say "apple" word is banned, if you send a message saying "Im eating a pineapple" your message will be banned because it contains "apple" somewhere in the string regardless the rest. What I want to do is check each word in isolation, not if the string contains the patern, so "Im eating an apple" should be banned for exemple and not "Im eating a pineapple".

I tried add blank spaces before and after each word in my array like " apple " but it doesn't work cause it will say the word is fine if you dont put the spaces in the message. I had another idea which was to add in my condition something to check if character before and after the word are spaces or null like && word 1 = " " && word-1 = " " but idk if it's doable. Here is a sample of my code :

const bannedWords = [                //banned words list
  "apple",
  "car",
  "test"
  ];

var word2parse = document.getElementById("word2parse");
var output = document.getElementById("display");

function parse(){

  if (bannedWords.some(word => word2parse.value.includes(word))){    //if message contain one  
  output.innerHTML = "this word is banned";                          //of the word in the array
  }
  else{
  output.innerHTML = "this word is fine";
  }
}
<input type = "text" id = "word2parse">
<input type = "button" onclick = "parse()" value = "Parse">
<p id = "display"></p>

CodePudding user response:

You can use a regular expression for that with word boundaries (\b):

const bannedWords = [                //banned words list
  "apple",
  "car",
  "test"
];
const bannedRegex = RegExp("\\b("   bannedWords.join("|")   ")\\b");

var word2parse = document.getElementById("word2parse");
var output = document.getElementById("display");

function parse() {
  if (bannedRegex.test(word2parse.value)) {
    output.innerHTML = "this text contains a banned word";
  } else{
    output.innerHTML = "this text is fine";
  }
}
<input type = "text" id = "word2parse">
<input type = "button" onclick = "parse()" value = "Parse">
<p id = "display"></p>

CodePudding user response:

I think Regexp with word boundary would help here. That \b below excludes pineapple from serach.

[...'apple pineapple'.matchAll(/apple/g)].length
2
[...'apple pineapple'.matchAll(/\bapple/g)].length
1 
  • Related