Use .indexof to Check for Multiple Strings with Array [duplicate] - javascript

This question already has answers here:
How to check if a string contains text from an array of substrings in JavaScript?
(24 answers)
Closed last year.
I am attempting to embed a chat widget if utm_source=VALUE (any of these values)
Here is the surrounding code:
var ref1 = document.referrer;
IF STATEMENT HERE
{
alert("Welcome to Ellas Bubbles");
s1.src='https://embed.tawk.to/620675459bd1f31184dc28c0/1frkjk5mj';
}
You can test it here: https://ellasbubbles.com
I have tried the following, which is only working on 'ccov':
if ((ref1.indexOf('ccov') || ref1.indexOf('top10') || ref1.indexOf('cenf') || ref1.indexOf('aip') || (getcookie('track-page-1').indexOf('ccov')>-1) || (getcookie('track-page-1').indexOf('top10')>-1) || (getcookie('track-page-1').indexOf('cenf')>-1) || (getcookie('track-page-1').indexOf('aip')>-1)) > -1)
I have also tried this:
if ((ref1.indexOf('ccov' || 'top10' || 'cenf' || 'aip') || (getcookie('track-page-1').indexOf('ccov' || 'top10' || 'cenf' || 'aip')>-1)) > -1)
{
s1.src='https://embed.tawk.to/620675459bd1f31184dc28c0/1frkjk5mj';
}
Which is also only working on the first value, 'ccov'.
I have also tried this:
if ((ref1.indexOf('ccov', 'top10', 'cenf', 'aip') || (getcookie('track-page-1').indexOf('ccov', 'top10', 'cenf', 'aip')>-1)) > -1)
Which is also only working on the first value
Is there a better way to go about this?

I think your statements are incomplete. Before each || you need to condition to be satisfied. I’m writing on my phone so sorry this isn’t as specific but you need the >-1 before every ||. So instead of
X || Y < z
I think You need
X < z || y < z.

Related

How to check if the URL contains a number? [duplicate]

This question already has answers here:
Check whether an input string contains a number in javascript
(14 answers)
Closed 2 years ago.
I am using window.location.href.indexOf to check if URL contains a string and works very well for something like this:
if (window.location.href.indexOf("franky") > -1) {
alert("your url contains the name franky");
But it doesn't work to check if URL contains any number.
The following always calls the alert, even if no number is in the URL.
if (
window.location.href.indexOf("0") === -1 ||
window.location.href.indexOf("1") === -1 ||
window.location.href.indexOf("2") === -1 ||
window.location.href.indexOf("3") === -1 ||
window.location.href.indexOf("4") === -1 ||
window.location.href.indexOf("5") === -1 ||
window.location.href.indexOf("6") === -1 ||
window.location.href.indexOf("7") === -1 ||
window.location.href.indexOf("8") === -1 ||
window.location.href.indexOf("9") === -1
)
{ alert("false"); }
As gaetanoM suggested, a regular expression would be the easiest way to do it.
if (window.location.href.match(/\d/)) {
alert('contains a number');
} else {
alert('does not contain a number');
}

Multiple OR conditions for an IF statement

Am I doing the multiple OR conditions for an IF statement the right way?
var A0minWidth = 841;
var A0minHeight = 1189;
var A0minWidthBleed = 847;
var A0minHeightBleed = 1195;
UploadedDocNameHeightMM = //(get it from the database)
UploadedDocNameWidthMM = //(get it from the database)
if(UploadedDocNameHeightMM < parseFloat(A0minHeight) || UploadedDocNameWidthMM < parseFloat(A0minWidth) || UploadedDocNameWidthMM > parseFloat(A0minWidthBleed) || UploadedDocNameHeightMM > parseFloat(A0minHeightBleed))
{
//do this
alert ("Yes! one of those.")
}
Help!
It depends on what your code is supposed to do of course, but syntactically this is correct - e.g. no need to wrap each each expression that is an operand to the logical-OR operators in parentheses like this:
if ((UploadedDocNameHeightMM < parseFloat(A0minHeight)) || (UploadedDocNameWidthMM < parseFloat(A0minWidth)) || (UploadedDocNameWidthMM > parseFloat(A0minWidthBleed)) || (UploadedDocNameHeightMM > parseFloat(A0minHeightBleed)))
{
alert("Yes! one of those.");
}
Also, the || operator will short-circuit evaluate. Basically it will not evaluate expressions to the right of any expression that evaluates to true.
For more information on || and other JavaScript logical operators including examples check out Mozilla's overview or search on JavaScript logical operators.
The syntax is correct.
However:
parseFloat is not necessary here
Are you sure the two first tests are correct (==> Don't you need to check if UploadedDocNameHeightMM > A0minHeight instead of < ?)

Using multiple logical "or" operators

Other than using a switch statement (or writing if(x === 2 || x === 3 || x === 4) etc), is there any way to implement multiple "or" (||) operators?
E.g.:
if(x === 2 || 3)
alert("Yes");
This alerts for every value of x
The closest you can probably come is to do something like this:
if ([2,3].indexOf(x) > -1){
}
DOCS
Of course that will require a shim for IE 8 and below, if that's an issue for you.
Standard approach for large number of choices is to use dictionary/hash set/hash table depending on language.
For JavaScript both array and object would work:
var isPresent = [];
isPresent[2] = true;
isPresent[43] = true;
if (isPresent[x])...
For small number of items Adam Rackis' answer with linear search is much more readable
[2,3].indexOf(x)

How to check if the elements of an array are identical in javascript (more than 2 elements)

I am trying to make sure that a phone# is not all identical characters, example 1111111111
The code I am using works but there has to be a cleaner way. I've tried loops but that only compares two consecutive characters at a time. This is what I am using now:
if (MainPhone.value != "")
{
if ((MainPhone.value == 1111111111) || (MainPhone.value == 2222222222) || (MainPhone.value == 3333333333) || (MainPhone.value == 4444444444) || (MainPhone.value == 5555555555) || (MainPhone.value == 6666666666) || (MainPhone.value == 7777777777) || (MainPhone.value == 8888888888) || (MainPhone.value == 9999999999) || (MainPhone.value == 0000000000))
{
window.alert("Phone Number is Invalid");
MainPhone.focus();
return false;
}
}
I found this recommendation for someone else' question but could not get it to work.
var dup = MainPhone.value.split('');
if all(dup == dup(1))
I would try something like this:
var phone = '11111211';
var digits = phone.split('').sort();
var test = digits[0] == digits[digits.length - 1];
Simply sort the array and compare first and last element..
You can use a regular expression like this to check if all characters are the same:
^(.)\1*$
Example:
var phone = '11111111';
if (/^(.)\1*$/.test(phone)) {
alert('All the same.');
}
Demo: http://jsfiddle.net/Guffa/3V5en/
Explanation of the regular expression:
^ = matches start of the string
(.) = captures one character
\1 = matches the first capture
* = zero or more times
$ = matches end of the string
So, it captures the first character, and matches the rest of the characters if they are the same.

Shorten JS if or statement [duplicate]

This question already has answers here:
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 6 years ago.
Is there anyway to shorten something like this in Javascript: if (x == 1 || x == 2 || x == 3 || x == 4) to something like if (x == (1 || 2 || 3 || 4)) ?
You can use use Array.indexOf
[1,2,3,4].indexOf(x) !== -1
You can also use objects as some kind of hash map:
//Note: Keys will be coerced to strings so
// don't use this method if you are looking for an object or if you need
// to distinguish the number 1 from the string "1"
my_values = {1:true, 2:true, 3:true, 'foo':true}
my_values.hasOwnProperty('foo')
By the way, in most cases you should usi the "===" strict equality operator instead of the == operator. Comparison using "==" may do lots of complicated type coercion and you can get surprising results sometimes.
If your cases are not that simple to be expressed by this:
if (1 <= x && x <= 4)
You could use an array and indexOf:
if ([1,2,3,4].indexOf(x) > -1)
Note that indexOf might need to be re-implemented.
Not without writing a function that takes an array as an input and returns true/false, or some sort of array search. It would be hard to maintain/other devs to read. And it would be significantly slower. So just stick with the semantically correct longer version.
Also a good way to see if anything can be shortened significantly is to run it through the close compiler and see what it comes out with.
How about:
if (x > 0 && x < 5) {
}
You could write a function:
function isAny(x) {
for (var i = 1; i < arguments.length; ++i)
if (arguments[i] === x) return true;
return false;
}
Then you can say:
if (isAny(x, 1, 2, 3, 4)) { /* ... */ }
(Whether to use "===" or "==" would depend on the exact semantics you want.)

Categories

Resources