Forbidden words checker - javascript

i'm new on stack but here's my question:
I'm trying to check if an html input's value has one of my forbidden words that are in a array.
I've tried:
Using split(), transforming the input.value in a array and then comparing each other.
Using toString() to transform the array into a string, and then comparing both.
Using a string with all the words ("wordone wordtwo wordthree") instead an array(["wordone","wordtwo", "wordthree"]).
Spliting the string above then comparing.
And some variants of the examples above, but always checking with includes() method.
I'm really not understanding why nothing works.
When i put only one forbidden word in the array, it works.
If i write more than one word on the input element, even if there's only one word in the array, it not works.
Here's the HTML:
<input id="field" type="text" size="100">
<button id="check">check</button>
<p id="announce">Message</p>
Here's the JS:
fieldIncludes() {
let field = document.querySelector('#field'); //gets the field
let btn = document.querySelector('#check'); //gets the check-field button
let messageBox = document.querySelector('#announce'); // gets the <p> to show a message
let forbiddenWords = ['wordOne', 'wordTwo', 'wordThree'];
btn.addEventListener("click", () => {
if (field.value.includes(forbiddenWords)){
messageBox.innerHTML = "Forbidden!";
} else {
messageBox.innerHTML = "Okay :)";
}
})
}
Please ignore that the JS is in a class.

hope i didn't get you wrong.
var str = 'you plays like a noob';
function inspect_string(str, arr){
flag = false;
arr.forEach(ar=>{
flag = str.match(new RegExp(ar)) ? true : false;
});
return flag
}
// var arr = ['noob', 'trash'];
var arr = ['nice', 'good'];
console.log(inspect_string(str, arr));

The argument to includes() should be a single string to check, it doesn't automatically loop over the array. You can use the .some() method to check if any of them match.
if (forbiddenWords.some(word => field.value.includes(word))) {
messageBox.innerHTML = "Forbidden!";
} else {
messageBox.innerHTML = "Okay";
}

Related

Advanced search in Javascript

I try to implement a search bar in a project.
It should just search for the entries and hide the rows, when the input doesn't match.
This is what I did and it's working.
_searchCalls() {
let rows = document.querySelector('call-journal').shadowRoot.querySelectorAll('#row')
let callEntries = document.querySelector('call-journal').shadowRoot.querySelectorAll('call-entry')
for(let i = 0; callEntries.length > i; i++) {
let tmp = callEntries[i].shadowRoot.querySelector('.callInfo')
let entries = tmp.textContent.toLowerCase()
let dates = callEntries[i].shadowRoot.querySelector('.dateWrapper').textContent
let userInput = this._getSearchInput().toLowerCase()
if(!(entries.includes(userInput) || dates.includes(userInput))) {
rows[i].classList.add('hide')
} else {
rows[i].classList.remove('hide')
}
}
}
I want to extend the search. So what I write 'Bill Gates' it works, but not when I write 'Gates Bill'.
Any help would be much appreciated.
Reverse your logic.
Instead of telling each row to show/hide,
make each row listen to the change/keyup event on the search box.
Yes, that means an addEventListener for every row.
Search: <input type="text" value="foo bar">
<row-item>qux, baz, foo, bar</row-item>
<row-item>corge, foo</row-item>
<row-item>baz, quuz, bar, quux, foo</row-item>
<row-item>baz, corge, bar, quuz</row-item>
<row-item>bar</row-item>
<row-item>corge, baz, quux</row-item>
<row-item>baz, corge</row-item>
<row-item>foo</row-item>
<row-item>bar, quux, corge, foo</row-item>
<style>
row-item { display: block }
</style>
<script>
customElements.define("row-item", class extends HTMLElement {
connectedCallback() {
document.querySelector("input")
.addEventListener("keyup",(evt) => this.match(evt.target.value));
this.match("foo bar"); // for testing!
}
match(search) {
let findWords = search.trim().split(" ");
let rowWords = new Set(this.innerHTML.split(/, /));
let matched = findWords.map(word => rowWords.has(word))
.filter(Boolean) // remove false values
.length == findWords.length;
this.style.backgroundColor = matched ? "lightgreen" : "lightcoral";
}
})
</script>
Like the first comment from suggested, it sounds like you are trying to match all words in the search input to the rows/entries.
First, to break the input into an array of multiple terms, you could use the String method .split(' ') to split on spaces. For example:
"Bill Gates".split(' ')
This would result in an array that looks like ['Bill', 'Gates']
Then, you could loop through the array of search terms you created with .split() and check if they exist in a row/entry with the String .includes() method (like you're checking right now on the userInput string).

How to check text input changes for certain words?

I need to create a web page on which I have added a text field. I have set an ID to the text field (say, 'custom'). Now, I want to modify the webpage if the text field contains certain words.
For example, if the text field contains a word, say apple, I want to do something.
If the text field contains ball, I want to do something else.
And so on.
I had found this:
<script>
var check=document.getElementById("custom").value == "text_value";
//check will be true or false
if (check){ //do something if true}
if(!check){//do something if false}
</script>
I don't even know if it's correct or not, but, I realised, it won't be able to manage multiple conditions. Because, if the text contains apple, it won't contain ball, it will create wierd behaviour.
So, how can I achieve this?
Check out the following Vanilla JavaScript (plain JavaScript) example.
I.e. enter bla bla apple and you will get the expected result.
function doSomething() {
var text = document.getElementById("myInput").value;
if (text.includes("apple")) {
console.log("do something special because text contains apple");
}
else if (text.includes("ball")) {
console.log("do something special because text contains ball");
}
else {
console.log("text contains no special word");
}
}
Enter text: <input type="text" id="myInput" onkeyup="doSomething()">
Can you please run the code snippet below.
The trigger is onkeyup and was selected for demonstration purposes. You can change it as per your requirement, for example, run the javascript function watchWords upon pressing a button.
function watchWords()
{
var watch_words = ['apple', 'lemon', 'watermelon'];
var textvalue = document.getElementById('name').value;
for(var i=0; i<watch_words.length; i++) {
if (~textvalue.indexOf(watch_words[i])){
if(watch_words[i] == 'apple'){
console.log('Apple was found');
}
if(watch_words[i] == 'lemon'){
console.log('Lemon was found');
}
if(watch_words[i] == 'watermelon'){
console.log('Watermelon was found');
}
}
}
}
<input type="text" name="name" id="name" onkeyup="watchWords()" />
One option is to use an object indexed by the .values you want to identify, whose property values are the functions you you want to run for each, eg:
const objOfFns = {
apple() {
console.log('Apple!');
},
ball() {
console.log('Ball!');
bounceBall();
}
};
const { value } = document.getElementByid('custom');
const possibleFn = objOfFns[value];
// check hasOwnProperty to avoid accidentally referencing Object.prototype methods
if (possibleFn && objOfFns.hasOwnProperty(value) {
possibleFn();
}
Using jQuery on keyup event listener and includes function:
$("#custom").on("keyup", function() {
if (this.value.includes("apple")) {
// do something
}
});
The code above will check the custom input each time the user presses a key and execute the if block if the input string contains the word apple.
<script>
function common(arr1, arr2) {
var newArr = [];
newArr = arr1.filter(function(v){ return arr2.indexOf(v) >= 0;})
newArr.concat(arr2.filter(function(v){ return newArr.indexOf(v) >= 0;}));
return newArr;
}
var string = document.getElementById("custom").value;
var items = string.split(" ");
var yourlist = ["apple", "banana", "tomato"];
var intersection = common(yourlist, items);
for(i=0; i<intersection.length; i++){
console.log(intersection[i]);
var z = yourlist.indexOf(intersection[i]);
/* Your Logic Goes Here.. */
if(z == 0){
/* do something */
}else{
/* do something else */
}
}
</script>
Function Credits - https://gist.github.com/IAmAnubhavSaini

loop through array to find matches and return every possible solution

I have a small input field where this code gets activated everytime a key is pressed inside it. But it now only prints "found something" when the name exacly matches what you type in the input field.
How can change a part that when I type something like "b" it already removes the matches where there is no "b" in the name is and print every possible matches that still have a "b".
My small code to find the match.
Info is my json big array where I can loop through all the names with info[i].name
var textInput = $findperson.find('input').val();
console.log(textInput);
for (i = 1; i < info.length; i++) {
if (textInput === info[i].name) {
console.log('found something');
}
}
Set Flag if found any match and print them, otherwise print found nothing,
for gi g mean search globally and i mean ignore case sothat A will match a and vise verse.
var textInput = $findperson.find('input').val();
console.log(textInput);
found = false
for (i = 1; i < info.length; i++) {
if (info[i].name.match(new RegExp(textInput,"gi")) ) {
console.log(info[i].name);
found = true
}
}
if(!found){
console.log("found nothing")
}
I would use regex like this:
var textInput = $findperson.find('input').val();
var regex = new Regexp(".*("+textInput+").*","i");
var filtered = info.filter(function (current) {
return current.name.match(regex);
});
console.log(filtered);
Just use indexOf to search for one String within another:
if(info[i].name.indexOf(textInput) != -1) {
indexOf will return -1 if String isn't found within the other.
You can try searching for some letters in one of the results 'balloon', 'ball', 'apple' in the example below:
var results = ['balloon', 'ball', 'apple'];
function filterResults() {
var input = document.getElementById('input').value;
var resultsFiltered = results.filter(function(a) {
return a.indexOf(input) != -1;
});
var result = ''; resultsFiltered.map(function(a) {
result += a + '<br/>';
}); document.getElementById('result').innerHTML = result;
}
<input id='input' onkeyup='filterResults();'/>
<div id='result'></div>

How to detect if a user input has been repeated?

I'm trying to make hangman in javascript and I want to check if the user has used a letter already. I made a var letterGuessValue = to 0 and if they add an input it = 1. I know this would say know to everything if i got it to work (it doesn't even do anything) but am I on the right track maybe? Here's my code. http://jsbin.com/aWOnAfe/5/edit
I would say add an input to a list and whenever they add another input (aka letter), check this list to see if it is already in there. If it is, then its because they've already used that letter before. If not, then it is a new letter.
I don't see where the difficult part is.
http://jsfiddle.net/DerekL/jgqQ9/
Sample code
var used = {};
$("input").keyup(function(){
var val = this.value;
alert( used[val] ? "Used" : "Not used" );
this.value = "";
used[val] = true;
});
How it works
Assign true to used.LETTER when a letter is entered. Before assigning it though, if it was undefined then it hasn't been used. If it is true then it is used.
Sometimes developers tend to use an Array to record pressed keystrokes when doing key combinations, but in this case, iterating an Array would require both more memory and computation power. A simple object is an enough fit.
Use an array to store all of the used letters and function like this to add new ones.
var inputs = []
function addLetter(letter){
var used = false;
for(var i = 0; i < inputs.length; i++){
if(inputs[i] == letter){
used = true;
break;
}
}
if(!used){
inputs.push(letter);
}
}
The easiest way is to append each letter to a string, like this:
var letters = '';
var letterPressed = 'X'; // uppercase it if appropriate for your language
if (letters.indexOf(letterPressed) > -1)
{
// you already pressed it
}
else
{
letters += letterPressed;
}
You can also use an array to store your list of presses, although IMO that's overkill.

validate 2 dropdowns (only some combinations valid)

I am completely new to JavaScript.
I have size and color dropdowns on a page for users to order a product, but only certain combinations are available i.e. pink is the only color in large sizes.
I thought I'd make an array of allowed sizes and test the user input against these.
If the choice is invalid then I want a popup to tell the user why.
In the real world I'll use SQL & PHP to create the array of allowed choices, in the example below I've hard coded 3 valid choices for testing. Unfortunately the code below doesn't do anything.
I'm sure it's a simple newb mistake. I really don't know what I'm doing :)
Can somebody help me out?
The validation function is supposed to happen when user clicks the form submit...
<form id="form1" name="form1" method="post" onsubmit="return validate_form()"
action="cart.php">
Here's the function:
<script type="text/javascript">
function validate_form() {
var allowed = new Array();
allowed[0]="10,beige";
allowed[1]="10,black";
allowed[2]="10,pink";
var chosenColInd = document.getElementById("colID");
var chosenColText = colID.options[colID.selectedIndex].text;
var chosenSizeInd = document.getElementById("sizeID");
var chosenSizeText = sizeID.options[sizeID.selectedIndex].text;
var chosenSizeCol = chosenSizeText+","+chosenColText;
var found = "false";
for ( var i = 0; i < allowed.length; i++ ) {
if (allowed[i]=chosenSizeCol) {
found = "true";
}
}
if (found = "false") {
alert( 'The variation you have selected is currently unavailable. Please select another.' );
return false;
} else {
return true;
}
}
</script>
There are a few lines where you use the assignment operator (that is single equals =) instead of one of the equality operators (that is double or triple equals, triple is usually preferred in JavaScript). Example:
if (found = "false") {
Would appear to be the problem at first sight - it's an assignment not a comparison :) use triple equals === instead of single:
if(found === "false") {
Also, consider the following (commented) updates to your code, which reflects more the typical style of JavaScript code:
function validate_form() {
//no need to use new Array(), use array literal instead
var allowed = [
"10,beige",
"10,black",
"10,pink"
];
var chosenColInd = document.getElementById("colID");
var chosenColText = colID.options[colID.selectedIndex].text;
var chosenSizeInd = document.getElementById("sizeID");
var chosenSizeText = sizeID.options[sizeID.selectedIndex].text;
var chosenSizeCol = chosenColText+","+chosenSizeText;
var found = "false";
for ( var i = 0; i < allowed.length; i++ ) {
//use equality operator instead of assignment
if (allowed[i]===chosenSizeCol) {
found = true; //may as well use a boolean rather than string
break; //exit loop early, no need to continue if we've already found
}
}
if (!found) { //no need to do a comparison with already boolean values
alert( 'The variation you have selected is currently unavailable. Please select another.' );
}
//may as well just return found here now that we're using a boolean
return found;
}

Categories

Resources