Check if array does not contain string js

Active3 hr before
Viewed126 times

7 Answers


Searching for a primitive value like string or number inside of an array is simple: just use array,includes(value) method

Example_snippet/controller/utility/_contain.js/ const hasValue = array.include. . .
const hasValue = array.includes(value[, fromIndex]);
load more v

Here's a Code Recipe to check if a #JavaScript array contains a value, You can use the new array includes method 😋 For older browsers and IE, you can use indexOf 👍,Stack Overflow: How do I check if an array includes a value in JavaScript? ,Support for includes is really good for all modern browsers

Example_snippet/controller/utility/_contain.js/ const array = ['🥗', '🍔', '🍰. . .
const array = ['🥗', '🍔', '🍰'];

// Modern Browser
array.includes('🍰'); // true

// Older Browser
array.indexOf('🍰') !== -1; // true
load more v

Example_snippet/controller/utility/_contain.js/ var fruits = ["Banana", "Orang. . .
var fruits = ["Banana", "Orange", "Apple", "Mango"];

var n = fruits.includes("Mango"); // true

var n = fruits.includes("Django"); // false
load more v

The includes() method returns true if an array contains a specified element, otherwise false,,includes() is case sensitive

Example_snippet/controller/utility/_contain.js/ includes(). . .
Step 2 continued with true. . .
Step 3 continued with false. . .
load more v

Probably easier to use a regex, but if you really want to do it with an array, you'd need to loop through each character in the string and check if all of them are in the array, Something like username

Example_snippet/controller/utility/_contain.js/ if (username.indexOf(allowed) . . .
if (username.indexOf(allowed) != -1) {
Step 2 continued with if (!/^[a-z0-9_-]*$/i.test(use. . .
if (!/^[a-z0-9_-]*$/i.test(username)) {
Step 3 continued with /^[\w-]+$/ . . .
load more v

JavaScript Array includes(),In the above program, the includes() method is used to check if an array contains a specified value,,In this example, you will learn to write a JavaScript program that will check if an array contains a specified value

Example_snippet/controller/utility/_string.js/ // program to check if an arra. . .
// program to check if an array contains a specified value

const array = ['you', 'will', 'learn', 'javascript'];

const hasValue = array.includes('javascript');

// check the condition
if (hasValue) {
   console.log('Array contains a value.');
} else {
   console.log('Array does not contain a value.');
load more v

Example_snippet/controller/utility/_string.js/ function checkInput(input, wor. . .
function checkInput(input, words) {
   return words.some(word => input.toLowerCase().includes(word.toLowerCase()));

console.log(checkInput('"Definitely," he said in a matter-of-fact tone.',
   ["matter", "definitely"]));
load more v