Javascript if does not contain

JQuery: if element does not contain text

I am trying to write a statement along the lines of: ‘if given element does not contain the following text, do something’. I have tried using :contains as such:

var openingHours = $('.opening-listing:nth-child(' + new Date().getDay() + ')'); if($(openingHours + ':contains("Closed")').length > 0) < //Do something >

But am getting syntax errors. Would anyone know what I’ve done wrong here, or if there is a better way of going about this?

What syntax error are you getting? Also can you check if you are getting anything in openingHours var before the if condition?

3 Answers 3

openingHours is a jQuery object, not a css selector. You can use .text() , .indexOf() , which :contains() uses internally

if (openingHours.text().indexOf("Closed") === -1) < // do stuff >
var openingHours = $('.opening-listing:nth-child(' + new Date().getDay() + ')'); if($(openingHours).find(':not(:contains("Closed"))').length > 0) < //Do something >

They way I understand your question is that; you have an HTML element with some content (text or number). And you want to use that content in decision making such as if-statement.

Here is an example of the code I made in repl.it, click here.

I give each element a unique id name, so that I can call it in JavaScript for decision-making. Then I add onClick which invokes a function in JavaScript.

Читайте также:  vertical-align

Next step is to use document.getElementById(tagName).value which receives the content you have written in the inputfield after you click on submit button. And set the value into a next variable instead of copying the whole line of code. Last but not least, I have also added an example if you have jQuery library, I prefer using jQuery approach because it is less code and easier to understand for beginners.

Источник

Javascript if does not contain

Last updated: Dec 26, 2022
Reading time · 4 min

banner

# Table of Contents

# Check if Array Doesn’t contain a Value in JavaScript

Use the logical NOT (!) operator to negate the call to the includes() method to check if an array doesn’t contain a value.

The negated call to the Array.includes() method will return true if the value is not in the array and false otherwise.

Copied!
const arr = ['a', 'b', 'c']; const notIncludesD = !arr.includes('d'); console.log(notIncludesD); // 👉️ true const notIncludesC = !arr.includes('c'); console.log(notIncludesC); // 👉️ false if (notIncludesC) console.log('✅ the value c is NOT contained in the array'); > else // 👇️ this runs console.log('⛔️ the value c is contained in the array'); > // --------------------------------------- // ✅ Check if an object is not contained in an array const arr2 = [id: 1>, id: 2>, id: 3>]; const notContained = arr2.every(obj => return obj.id !== 4; >); console.log(notContained); // 👉️ true

check if array does not contain value

We used the logical NOT (!) operator to negate the calls to the Array.includes() method.

This approach allows us to check if a specific value is not contained in the array.

Our first example checks if the value d is not contained in the array and returns true .

Copied!
const arr = ['a', 'b', 'c']; const notIncludesD = !arr.includes('d'); console.log(notIncludesD); // 👉️ true const notIncludesC = !arr.includes('c'); console.log(notIncludesC); // 👉️ false

checking if the value is not contained in the array

The string c is contained in the array, so the expression returns false .

Here are some more examples of using the logical NOT (!) operator.

Copied!
console.log(!true); // 👉️ false console.log(!false); // 👉️ true console.log(!'hello'); // 👉️ false console.log(!''); // 👉️ true console.log(!null); // 👉️ true

using logical not operator

You can imagine that the logical NOT (!) operator first converts the value to a boolean and then flips the value.

The falsy values in JavaScript are: null , undefined , empty string, NaN , 0 and false .

If you have to perform the test often, define a reusable function.

Copied!
function notIncludes(array, value) return !array.includes(value); > const arr = ['a', 'b', 'c']; console.log(notIncludes(arr, 'c')); // 👉️ false console.log(notIncludes(arr, 'd')); // 👉️ true console.log(notIncludes(arr, 'z')); // 👉️ true

The notIncludes() function takes an array and a value as parameters and checks if the value is not contained in the array.

The function returns true if the value is not contained in the array and false otherwise.

You can also use the indexOf() method to check if a value is not contained in an array.

# Check if Array Doesn’t contain a Value using indexOf()

This is a two-step process:

  1. Use the indexOf() method to get the index of the value in the array.
  2. If the method returns -1 , the array doesn’t contain the value.
Copied!
const arr = ['a', 'b', 'c']; if (arr.indexOf('d') === -1) // 👇️ this runs console.log('The value d is NOT contained in the array'); > else console.log('The value d is contained in the array'); > console.log(arr.indexOf('c')); // 👉️ 2 console.log(arr.indexOf('z')); // 👉️ -1

check if array does not contain value using indexof

The Array.indexOf method returns the index of the first occurrence of the supplied value in the array.

If the value is not contained in the array, the method returns -1 .

Our if statement checks if the Array.indexOf() method returned -1 .

If you have to perform the test often, define a reusable function.

Copied!
function notIncludes(array, value) return array.indexOf(value) === -1; > const arr = ['a', 'b', 'c']; console.log(notIncludes(arr, 'c')); // 👉️ false console.log(notIncludes(arr, 'd')); // 👉️ true console.log(notIncludes(arr, 'z')); // 👉️ true

The function takes an array and a value as parameters and returns true if the value is not contained in the array.

If you need to check if an object is not contained in an array, use the Array.every() method.

# Check if an object is not contained in an array in JavaScript

To check if an object is not contained in an array:

  1. Use the Array.every() method to iterate over the array.
  2. Check if each object doesn’t have a property equal to the specific value.
  3. The every() method will return true if the object is not in the array.
Copied!
const arr2 = [id: 1>, id: 2>, id: 3>]; const notContained = arr2.every(obj => return obj.id !== 4; >); console.log(notContained); // 👉️ true if (notContained) console.log('The object is NOT contained in the array'); > else console.log('The object is contained in the array'); >

check if object is not contained in an array

The function we passed to the Array.every method gets called with each element of the array.

If all invocations of the callback function return a truthy value, then the Array.every() method returns true , otherwise, false is returned.

On each iteration, we check if the current object doesn’t have a specific value and return the result.

If the callback function we passed to the Array.every() method returns a falsy value, then Array.every() short-circuits also returning false .

If the Array.every() method returns true , then the object isn’t contained in the array.

If the method returns false , the object is contained in the array.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

How can I check that a string does not include the text of another string?

ES6 version of this is (check out answer from Allison):

The original accepted answer was:

var x = "home.subjects.subject.exams.exam.tests"; console.log(x.indexOf('subjects')); // Prints 5 console.log(x.indexOf('state')); // Prints -1 

You could use includes and negate it.

var include_flag = toState.name.includes("home.subjects.subject.exams.exam.tests"); return !include_flag; 

Using the JS includes method would probably be your best bet. I get I’m a little late in answering this question, but I was just googling this myself and came up with this answer after some fiddling with the code. This code will return true if toState.name does NOT include the string given.

Hope this helps anyone searching the same question I had!

But how could I check the toState.name does not include the string:

var strArr = "home.subjects.subject.exams.exam.tests.test".split("."); var name = "home.subjects.subject.exams.exam.tests"; var contains = false; strArr.reduce( function(prev, current) < if ( name.indexOf( current ) != -1 ) < contains = true; >return prev + "." + current; > ); if (contains) < alert( "yes it contains" ); >else

Have you actually tested it? var toState.name == «home.subjects.subject.exams.exam.tests»; incorrect, also reduce won’t be called if there is only 1 element in array, «home».split(«.») is 1 elem array

The original question contained a «?» ternary operator, so here is how to do it using a ternary operator.

Suppose you’re writing a poker game and have a rainbow flop. Now suppose you want the missing suit from the flop.

let flop = "3h Js 9c"; let missingSuit = !flop.includes("c") ? "c" : !flop.includes("d") ? "d" : !flop.includes("h") ? "h" : "s"; // missingSuit equals "d" 

I think you may be mistaking what looks like accidental punctuation included in the second to last code block for the beginning piece of a ternary operator. Nesting ternary operators in this way is difficult to read and generally frowned upon pretty unilaterally. If you’re going to do something like this (which I don’t recommend), you can make it more readable by encapsulating nested statements in parentheses and increasing the indentation for each new level of nesting.

Additionally, I’d recommend modeling cards with object-oriented programming (OOP) and not as strings. E.g., each card is an object with suit and value attributes, a card might belong to a deck, etc. Then you simply map over the dealt cards, access the suit attribute for each card, and find the missing suit via something like set difference.

Источник

How can I correctly check if a string does NOT contain a specific word?

I am currently trying to figure out how to solve the above named problem. Specifically I want to check if the string does not contain the word «stream» both in capital and lowercase letters. Here’s my code so far:

if (((gewaesser_name1.includes("Stream") == "false") || (gewaesser_name1.includes("stream") == "false")) && ((gewaesser_name2.includes("Stream") == "false") || (gewaesser_name2.includes("stream") == "false")))

The code does obviously not work as the results are not what I expect them to be. I also tried to use the indexOf method before using the following syntax variations:

gewaesser_name2.indexOf("stream") == -1 gewaesser_name2.indexOf("stream") < 0 

None of these variations seem to work for me. Could anyone please give me a hint what's the problem here? I used the indexOf method before many times but always when I wanted to check if a string did contain a specific word, not the other way round.

7 Answers 7

I suggest to use String+toLowerCase and check with String#indexOf , because it works in every browser.

if (gewaesser_name1.toLowerCase().indexOf("stream") === -1 && gewaesser_name2.toLowerCase().indexOf("stream") === -1)

indexOf() is the correct approach and the case issue can be easily resolved by forcing the test string to lower or upper case before the test using .toLowerCase() or .toUpperCase() :

const lookupValue = "stream"; const testString1 = "I might contain the word StReAm and it might be capitalized any way."; const testString2 = "I might contain the word steam and it might be capitalized any way."; function testString(testData, lookup) < return testData.toLowerCase().indexOf(lookup) === -1; >function prettyPrint(yesNo) < return "The string does" + (yesNo ? " NOT" : "") + " contain \"stream\" in some form." >console.log(prettyPrint(testString(testString1, lookupValue))); console.log(prettyPrint(testString(testString2, lookupValue)));

You may want to compare the returned results of your include() with strictly equal operands, === false or === true, it's much better practice however not really needed for this, just looks like you might benefit from knowing the different as comparing boolean to a string is an odd thing to do. I'd also not be checking "Stream" and "stream" try using toLowerCase() instead like so, var str1_check = gewaesser_name1.toLowerCase();

I'd check for stream using the lowercase "stream" as your new strings will all be in lower case, as well you want them to be separate from your initial variables as you may not want those names forced to lowercase. I'd use str1_check.includes("stream") to check if this string has the string "stream" in it, because this result is truthy or falsey you can perform your check like so.

if(str1_check.includes("stream")) < //this string contained stream >

I looks like your if logic here was if the first name doesn't contain "stream" or name 1 and 2 do not contain stream but your checking name 1 with lowercase "stream" and name 2 with uppercase "stream". it looks like you just want both names not to contain stream, this can be much more easily performed like this.

var str1_check = gewaesser_name1.toLowerCase(), str2_check = gewaesser_name2.toLowrCase();//this way you're not making multiple toLowerCase calls in your conditional and maintain the state of your two names. if(!str1_check.includes("stream") && !str2_check.includes("stream")) < //your code on truthey statement >

Источник

Оцените статью