Reputation: 183
I'm working on importing a word filter into a text input and I want to check if there is a match between a entire bad word that is in a array of words and a word that is inside a string, I will give an example of this...
List of bad words:
var bad_words = ['bad1', 'bad2', 'bad3'];
String with the value of text input:
var check_text = document.getElementById("text").value;
Lets say I have this word in my string (In this example I expect a false answer):
Here is bad2222
Lets say I have this word in my string (In this example I expect a true answer):
Here is bad2
Upvotes: 1
Views: 1012
Reputation: 1702
you can use the reverse technique to check it.
var bad_words = ['bad1', 'bad2', 'bad3'];
const check_text = 'Here is bad222';
const found = bad_words.find(word => check_text.split(' ').find(s=>s===word));
if(found){
console.log("True")
}else{
console.log("False")
}
Upvotes: 1
Reputation: 183
After a slight correction to the code,
This is the code that solved this problem for me..Thx to ritaj
<script type="text/javascript">
function check_val() {
var bad_words = ['bad1', 'bad2', 'bad3'];
var check_text = document.getElementById("text").value;
var error = 0;
if (check_text.split(' ').some(part => bad_words.includes(part))) {
error = error + 1;
}
if (error > 0) {
document.getElementById("bad_notice").innerHTML = "WARNING: Some Bad Words In Your Text";
}
else {
document.getElementById("bad_notice").innerHTML = "";
}
}
</script>
<div id="wrapper">
<textarea id="text" onKeyUp="check_val()" placeholder="Write Some Text Having Words 'bad1', 'bad2', 'bad3'"></textarea>
<p id="bad_notice"></p>
</div>
Upvotes: 2