I'm new to this, so I hope I can explain well enough what my problem is.
I've got a quiz and for an answer I created an input box. To get to another link you have to put two words in there but the order should not matter aka. it shouldn't matter if you write down "word1 word2" or "word2 word1", there should be only one rule: both words should be mentioned.
Is that possible?
My code so far:
function checkText()
{
var textwunf_1 = document.getElementById("wunf").value;
if(textwunf_1.toLowerCase() == "word1" && "word2"){
window.open("URL","_self");
}
else{
xxx
}
}
It does not work.
Before I only wanted to check if one word is used, like that:
var textwunf_2 = 'word1';
function checkText()
{
var textwunf_1 = document.getElementById("wunf").value;
if(textwunf_1.toLowerCase().indexOf(textwunf_2) == -1){
xxx
}
else{
window.open("URL","_self");
}
}
This worked but I can't use it for two words, because if I write
var textwunf_2 = 'word1 word2';
the order can't be 'word2 word1'...
Is there a solution to my problem?
Hopefully anyone can understand and help me, thank you!
Based on this commentary from the OP:
if the user types 3 words and two of them match with the answer, it should be also okay! even better if even 3 words or more are possible, as long as the user puts my two words in it..
You can check if both words are whitin the text using two conditions on the if:
textwunf_1.toLowerCase().indexOf("word1") >= 0
AND
textwunf_1.toLowerCase().indexOf("word2") >= 0
Try with the next code:
var textwunf_2 = 'word1';
var textwunf_3 = 'word2';
function checkText()
{
var textwunf_1 = document.getElementById("wunf").value;
if ((textwunf_1.toLowerCase().indexOf(textwunf_2) >= 0) &&
(textwunf_1.toLowerCase().indexOf(textwunf_3) >= 0))
{
window.open("URL","_self");
}
else
{
// xxx
}
}
Another approach:
var words = ["word1", "word2"];
function CheckWords() {
var inputWords = document.getElementById("wunf").value.split(' ');
var allWordsFound = true;
if (inputWords.length !== words.length) { return false; }
inputWords.forEach(function(word) {
if (words.indexOf(word.toLowerCase()) === -1) {
allWordsFound = false;
return;
}
});
return allWordsFound;
}
console.log(CheckWords());
I am creating a function that receive the text and check if include the answers(xx and yy), it doesn't matter the order. The ans list, can have 1,2 or more words, it will work.
let ans = ['xx','yy'];
function check(text){
text = text.toLowerCase();
let counter = 0;
ans.forEach((x) => {text.includes(x) && counter++ })
return counter === ans.length
}
console.log(check("aa bb")) // false
console.log(check("xx bb")) // false
console.log(check("aa yy")) // false
console.log(check("xx yy")) // true
console.log(check("yy xx")) // true
Related
i do not know why but this bit of code repeats itself 3 times when adding "questionwords" in the message, specifically it will run the else statement one and the main if statement twice.
bot.on('message', function(message) {
const words = message.content.split(' ');
if (words.includes('sans')) {
var questionwords = ['can', 'is', 'was', ];
for (i in questionwords)
if (!words.includes(questionwords[i])) {
if (message.author.bot) return;
var chance = Math.floor(Math.random() * 2);
if (chance == 0) {
message.channel.send('<:annoying_sans:520355361425981440>');
}
if (chance == 1) {
message.channel.send('<:sans:519723756403425294>');
}
} else {
var chance = Math.floor(Math.random() * 3);
if (chance == 0) {
message.channel.send('Maybe.');
}
if (chance == 1) {
message.channel.send('Yes.');
}
if (chance == 2) {
message.channel.send('No.');
}
}
}
});
To me it looks like you want to know if the words in the questionwords array were in the message. You already know how to check a single word using Array.includes(), but multiple words are more complicated.
If you just want to know if any word in the words array matches any word in the questionwords array, you can use Array.some():
var wereAnyFound = words.some(word => questionwords.indexOf(word) > -1);
// true or false
Maybe you want to make sure they are ALL in there, use Array.every():
var wereAllPresent = words.every(word => questionwords.indexOf(word) > -1);
// true or false
Maybe you want to know how many, or you want to get the matches (Array.filter()):
var matches = words.filter(word => questionwords.indexOf(word) > -1);
// an array of matches
var howMany = matches.length;
// number
Like James said in the comments, because there are three words in the questionwords array, your for loop will run three times. It will then reply once for each word.
However, if you remove the for loop and change
if (!words.includes(questionwords[i]))
to
if (!words.includes("can" || "is" || "was"))
you'll get the same result without the bot repeating itself, as it will search for "can" or "is" or "was" instead of "can" and then "is" and then "was".
I have two array which contains special characters am trying to compare each element of one array to another and get the element which is not found in another array. But my approach doesnt work properly
var specialChar = ['!','#','#','$','%','&'];
var $scope.inp= ['!','*','#'];
In my above example element '*' is not present specialChar
I tried this logic -
$scope.validateChar = function(specialChar,inp){
var i,j;
for (i=0,j=0; i<specialChar.length && j<inp.length;) {
if (specialChar[i] < inp[j]) {
++i;
} else if (specialChar[i] == inp[j]) {
++i; ++j;
} else {
$scope.notFoundChar = inp[j];
Error prompt showing special charatcter $scope.notFoundChar not found
$scope.charAllowedText = false;
return;
}
}
}
Please suggest what am doing wrong here?
You can filter out your Special char '*' like below
var result=[]
inp.map(function(inpElement){
if(specialChar.indexOf(inpElement)==-1)
result.push(inpElement)
})
console.log(result)
Below given code solves your problem.
var source = [1,2,3,4,5,6,7,8];
var target =[2,3,4,5,6,18,19];
var missingItems = [];
target.forEach(function(itemFromTarget){
var itemFound = false;
source.forEach(function(itemFromSrc){
if(itemFromTarget === itemFromSrc){
itemFound = true;
}
});
if (!itemFound) {
missingItems.push(itemFromTarget);
}
});
console.log(missingItems);
This question already has answers here:
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 6 years ago.
FYI: this is for a simple quiz with just a single input field for each answer.
I have the following Javascript if statement to check if the value entered into an input field is correct (in this case, if the value entered is 'england').
$('input').keyup(function () {
if ($(this).val().toLowerCase() == 'england') {
//Stuff
} else {
//Other Stuff
};
});
However, I want to allow for alternative spellings, so I need a few possible answers for each question - it seems sensible to use an array for this as so...
var ans1 = new Array();
ans1[0] = "England";
ans1[1] = "Englund";
ans1[2] = "Ingland";
How can I change my if statement to say 'if the input field value equals any of those values from the array, then do the following'?
Any help would be greatly appreciated! Thank you.
You can do this using .inArray():
if ($.inArray($(this).val(), ans1) > -1) {
//Stuff
}
Here, the code $.inArray($(this).val(), ans1) will search for a specified value for example England within an array ans1 and return its index (or -1 if not found).
UPDATE
For case-sensitive search:
First enter all the values in the array in Lower Case
Next use the code below:-
JS:
if ($.inArray($(this).val().toLowerCase(), ans1) > -1) {
//Stuff
}
You can use the 'indexOf' method of the array, this will return -1 if the value doesn't exist in the array:
//if answer is in array
if(array.indexOf(answer) != -1){
//do stuff
}else{
//do stuff
}
Try this
if(this.value.match(/^(England|Englund|Ingland)$/i))
using regex and gi modifier for case insensitive
Do like this
$('input').keyup(function () {
var ans1 = new Array();
ans1[0] = "England";
ans1[1] = "Englund";
ans1[2] = "Ingland";
for(int i=0;i<ans1.length;i++)
{
if ($(this).val().toLowerCase() ==ans1[i]) {
//Stuff
} else {
//Other Stuff
};
}
});
Perhaps you may consider checking each element of the array like that:
var ans1 = new Array();
ans1[0] = "England";
ans1[1] = "Englund";
ans1[2] = "Ingland";
$('input').keyup(function () {
for (var i = 0; i < ans1.length; i++) {
if ($(this).val().toLowerCase() == ans1[i]) {
//Stuff
} else {
//Other Stuff
};
}
});
Not the most beautiful solution, but it should work.
jQuery offers $.inArray:
var found = $.inArray('specialword', words) > -1;
Note that inArray returns the index of the element found, so 0 indicates the element is the first in the array. -1 indicates the element was not found.
put your spellings in an array like this:
words: [
"England"
"Inglund"
"Ingland"
]
Found will be true if the word was found.
If you want the index of the matched word delete > -1 from the line.
Your code would be like this:
$('input').keyup(function () {
var found = $.inArray($(this).val(), words);
found > -1 ? //Stuff : //otherStuff;
});
var tagAllowed = true;
var allowedTags =["Person","People","Dance","Word"];
if(tagAllowed === true) {
for(var i=0;i<allowedTags.length;i++){
var aTags = allowedTags[i];
if(input.val().toLowerCase() === aTags.toLowerCase()) {
tagged.append('<span unselectable="on" class="tagged '+colorize+'" title="Click To Delete">'+inputVal.trim()+'</span>');
tagSize = $('.tagged').length;
var ele = $('.tagged').last(),
subtract = parseInt(ele.outerWidth(true),10);
input.width(input.width() - subtract);
tagged.width(tagged.width() + subtract);
input.css('marginLeft','5px');
input.val("");
input.css('color','#000');
} else {
errorMess.children('span').remove();
errorMess.prepend('<span>'+errorProcess+'<span>');
errorMess.slideDown();
}
}
The following code works in a way, if the input.val() does not match it will show the custom alert errorMess and well even if the word matches it still shows the custom alert. I am wondering if maybe I am doing something wrong in my conditional. As I don't need the custom alert to appear if the words match.
If any suggestions please post. I know this isn't the best example with just a code, but I hope all of you get what I am trying to say. I just don't want the custom alert to appear if the two words match together.
You have the if-statement inside the for-loop. The input value will never equal more than one of the tags in the array. You could use a for-loop to set a boolean. Then the if-statement could follow the for-loop.
boolean isAllowedTag = false;
for(var i=0;i<allowedTags.length;i++){
var aTags = allowedTags[i];
if(input.val().toLowerCase() === aTags.toLowerCase()) {
isAllowedTag = true;
break;
}
}
if (isAllowedTag) {
// ...
} else {
errorMess.children('span').remove();
errorMess.prepend('<span>'+errorProcess+'<span>');
errorMess.slideDown();
}
}
add a break; after your input.css('color, '#000'); line. also, you should really change those last 3 lines to: input.val("").css({marginLeft:'5px', color:'#000'});. Making calls to .css() is slow, so it's better to do as much as you can in one call.
I have a three strings of categories
"SharePoint,Azure,IT";
"BizTalk,Finance";
"SharePoint,Finance";
I need to find a way to check if a string contains for example "SharePoint" and "IT", or "BizTalk" and "Finance". The tests are individual strings themselces.
How would i loop through all the category strings (1 - 3) and only return the ones which have ALL instances of the souce.
i have tried the following
function doesExist(source, filterArray)
{
var substr = filterArray.split(" ");
jQuery.each(substr, function() {
var filterTest = this;
if(source.indexOf(filterTest) != -1 )
{
alert("true");
return true;
}else
{
alert("false");
return false;
}
});
}
with little success...the code above checks one at a time rather than both so the results returned are incorrect. Any help would be great.
Thanks
Chris
UPDATE: here is a link to a work in progress version..http://www.invisiblewebdesign.co.uk/temp/filter/#
Try this:
function doesExist(source, filter)
{
var sourceArray = source.split(",");
var filterArray = filter.split(",");
var match = true;
$.each(filterArray, function(i, val) {
match = match && ($.inArray(val, sourceArray) != -1);
});
return match;
}
gives doesExist("SharePoint,Azure,IT", "SharePoint,IT")==true but doesExist("SharePoint,Azure,IT", "SharePoint,BizTalk")==false.
you could try something like:
if(filterArray.indexOf("SharePoint") > -1 && filterArray.indexOf("IT") > -1) {
...
}