JavaScript beginner, if a variable does not match to do something - javascript

Basically what I'm trying to do is write a greasemonkey script so that if a link on a page is not a link I have on an ignore list to just open the link, if it is on the list then reload the page after 5 seconds here is what I tried so far
var url1 = $("span.capsulelink a:eq(0) ").attr("href");
var ignoreList = ["example1.com","example2.com"]
if (url1 !== ignoreList) {
window.open(url1);
} else {
setTimeout(function() {
location.reload();
},5000);
}
I know it's the (url1 !== ignoreList) part I am having trouble with, I just can not seem to find the right expression for that. Like I do not know how to say if url1 is not on the ignoreList {do something}.

ignoreList.indexOf(url1) !== -1
This is another way of saying "is url contained in the ignoreList array?"
This is because the indexOf() method of Array returns the index of the element you're looking for, or -1 if the element doesn't exist.
To negate this, which is what you want to do, you write:
ignoreList.indexOf(url1) === -1
(i.e. is url1 not in ignoreList?)

This is a good question, because the answer really isn't intuitive.
When you're starting to learn javascript, some of the syntax patterns begin to look familiar.
But the javascript equivalent of PHP's
if (!in_array([ARRAY]));
simply isn't obvious at all - this is one syntax you just need to know.
Here is the javascript you're looking for:
if (ignoreList.indexOf(url1) !== -1) {
[RELOAD PAGE CODE HERE]
}
else {
[OPEN THE LINK CODE HERE]
}
Here's why it works:
ignoreList.indexOf([VALUE]) looks through the ignoreList array and searches through the array's items.
If one of those items is [VALUE], it returns the index of that item.
Importantly, if none of the items are [VALUE] it returns -1.
So, in order to establish that at least one of the items is [VALUE], you have to verify that the returned index definitely isn't -1.
Consequently the condition you need to check for is:
if (ignoreList.indexOf(url1) !== -1)

Related

javascript filter elements not found in second array

solved: requires explicit return statement for each filter. I thought the single boolean in each filter would be clear enough. by #adiga
I want to find the elements in one array (dcm) that are not found in a second array (vari). I want to match only two elements, vp (string type) and vd (date type). I've made sure there are some rows in dcm that meet the condition, but I'm getting no results.
Did I do up the code wrong? is there a better way to do this (.includes .contains .indexOf)?
var dcmm = dcm.filter(r=>{
vari.filter(rv=>{
rv[vp]+rv[vd] == r[dp]+r[dd]
}).length == 0
});
ps. sorrynotsorry to all the long variable name proponents out there. as well as the const-not-var proponents.
pps. this is google apps script not javascript, but I think the idea is the same.
Just in case, as it said #adiga you don't need return statements if you don't use {}.
Most likely this will work fine:
var dcmm = dcm.filter( r => vari.filter( rv => (rv[vp]+rv[vd] == r[dp]+r[dd]) ).length == 0 );

Troubles with the OR logical processor when coding discord bot

This is my current code, I'm wondering whether i have to use a mess of 'else if,' or if i can keep it compact.
if (message.content.toLowerCase().includes(`word`||`word2`||`word3`||`word4`||`wd`||`wd2`||`wd3`||`wd4`)){
message.reply('don\'t swear in front of me!');
message.delete({ timeout: 100 })
}})
The issue is that only the very first string, word, is being tested for.
All the other strings give no response when i type them into discord.
You have the right idea but you're using the || operator wrong. The || operator checks whether the statement on the left is false/null/undefined and if so, checks the statement on the right. The way you've defined it ('word'||'word2'||...), the operator takes the left statement, in this case the string 'word', and checks if it's false/null/undefined which it isn't because it's a string. Therefore it never checks any other words.
How I think you meant to use it, is like the following:
if (message.content.toLowerCase().includes(`word`) ||
message.content.toLowerCase().includes(`word2`) ||
message.content.toLowerCase().includes(`word3`) ||
...etc
){
// Code here
}
In theory this would work, but as you can see yourself this is far from clean and will get big and bulky with little effort. A better approach would be with using the Array.some() function which calls a function for each item in an array and returns true when one item passes the function. Take a look at the example below:
// Define an array of all the words that need to be checked.
const arrayOfBadWords = ['word', 'word2', 'word3', ...];
if (arrayOfBadWords.some(word => message.content.toLowerCase().includes(word))) {
message.reply('The message contains a blacklisted word.');
} else {
message.reply('The message looks absolutely fine.');
}

If path contains directory

I want to trigger a digital marketing tag on every page which falls under a particular URL path, say example.com/sachin under the sachin directory.
I've tried if (location.href === 'example.com/sachin.*/') but somehow the condition doesn't seem to work.
What will be the correct if condition for location.href if I want to cover all different resources with in the URL path say under sachin directory?
I presume you want to check if the URL contains example.com/sachin. It's highly rarely that any URL ever would contain 4 forward-slashes but what you would do is utilize indexOf.
if(location.href.indexOf("example.com/sachin/") != -1){
//Do something
}
This basically says, if "example.com/sachin/" is found somewhere in the given string(in location.href in this case) on an indexposition that is not -1(which means that it doesn't exist), then execute.
You need to use Regular Expressions to match needed resources.
Something like that:
if(location.href.match(/^http:\/\/example.com\/sachin\//)){
//your staff here
}
Another approach to check for a specific directory in a url.
function urlContains(url, value) {
return ~url.indexOf(value);
}
if (urlContains(location.href, "/sachin/")) {
// found
} else {
// not found
}
The indexOf method checks a string for the value that is passed and returns -1 if a result was not found.
Instead of checking for == -1 or != -1 you can use the Bitwise NOT operator ~ to convert -1 to 0, which is a falsy value, non-zero values are treated are truthy values in javascript.

How to make indexOf only match 'hi' as a match and not 'hirandomstuffhere'?

Basically I was playing around with an Steam bot for some time ago, and made it auto-reply when you said things in an array, I.E an 'hello-triggers' array, which would contain things like "hi", "hello" and such. I made so whenever it received an message, it would check for matches using indexOf() and everything worked fine, until I noticed it would notice 'hiasodkaso', or like, 'hidemyass' as an "hi" trigger.
So it would match anything that contained the word even if it was in the middle of a word.
How would I go about making indexOf only notice it if it's the exact word, and not something else in the same word?
I do not have the script that I use but I will make an example that is pretty much like it:
var hiTriggers = ['hi', 'hello', 'yo'];
// here goes the receiving message function and what not, then:
for(var i = 0; i < hiTriggers.length; i++) {
if(message.indexOf(hiTriggers[i]) >= 0) {
bot.sendMessage(SteamID, randomHelloMsg[Math stuff here blabla]); // randomHelloMsg is already defined
}
}
Regex wouldn't be used for this, right? As it is to be used for expressions or whatever. (my English isn't awesome, ikr)
Thanks in advance. If I wasn't clear enough on something, please let me know and I'll edit/formulate it in another way! :)
You can extend prototype:
String.prototype.regexIndexOf = function(regex, startpos) {
var indexOf = this.substring(startpos || 0).search(regex);
return (indexOf >= 0) ? (indexOf + (startpos || 0)) : indexOf;
}
and do:
var foo = "hia hi hello";
foo.regexIndexOf(/hi\b/);
Or if you don't want to extend the string object:
foo.substr(i).search(/hi\b/);
both examples where taken from the top answers of Is there a version of JavaScript's String.indexOf() that allows for regular expressions?
Regex wouldn't be used for this, right? As it is to be used for expressions or whatever. (my > English isn't awesome, ikr)
Actually, regex is for any old pattern matching. It's absolutely useful for this.
fmsf's answer should work for what you're trying to do, however, in general extending native objects prototypes is frowned upon afik. You can easily break libraries by doing so. I'd avoid it when possible. In this case you could use his regexIndexOf function by itself or in concert with something like:
//takes a word and searches for it using regexIndexOf
function regexIndexWord(word){
return regexIndexOf("/"+word+"\b/");
}
Which would let you search based on your array of words without having to add the special symbols to each one.

Javascript Regex and getElementByID

I'm trying to search for all elements in a web page with a certain regex pattern.
I'm failing to understand how to utilize Javascript's regex object for this task. My plan was to collect all elements with a jQuery selector
$('div[id*="Prefix_"]');
Then further match the element ID in the collection with this
var pattern = /Prefix_/ + [0 - 9]+ + /_Suffix$/;
//Then somehow match it.
//If successful, modify the element in some way, then move onto next element.
An example ID would be "Prefix_25412_Suffix". Only the 5 digit number changes.
This looks terrible and probably doesn't work:
1) I'm not sure if I can store all of what jQuery's returned into a collection and then iterate through it. Is this possible?? If I could I could proceed with step two. But then...
2) What function would I be using for step 2? The regex examples all use String.match method. I don't believe something like element.id.match(); is valid?
Is there an elegant way to run through the elements identified with a specific regex and work with them?
Something in the vein of C#
foreach (element e in
ElementsCollectedFromIDRegexMatch) { //do stuff }
Just use the "filter" function:
$('div[id*=Prefix_]').filter(function() {
return /^Prefix_\d+_Suffix$/.test(this.id);
}).each(function() {
// whatever you need to do here
// "this" will refer to each element to be processed
});
Using what jQuery returns as a collection and iterating through it is, in fact, the fundamental point of the whole library, so yes you can do that.
edit — a comment makes me realize that the initial selector with the "id" test is probably not useful; you could just operate on all the <div> elements on the page to start with, and let your own filtering pluck out the ones you really want.
You can use filter function. i.e:
$('div[id*="Prefix_"]').filter(function(){
return this.id.match(/Prefix_\d+_Suffix/);
});
You could do something like
$('div[id*="Prefix_"]').each(function(){
if($(this).attr('id').search(/do your regex here/) != -1) {
//change the dom element here
}
});
You could try using the filter method, to do something like this...
var pattern = /Prefix_/ + [0 - 9]+ + /_Suffix$/;
$('div[id*="Prefix_"]').filter(function(index)
{
return $(this).attr("id").search(pattern) != -1;
}
);
... and return a jQuery collection that contains all (if any) of the elements which match your spec.
Can't be sure of the exact syntax, off the top of my head, but this should at least point you in the right direction

Categories