There's nothing built-in that will do that for you, you'll have to write a function for it, although it can be just a callback to the some array method.
Two approaches for you:
- Array
somemethod - Regular expression
Array some
The array some method (added in ES5) makes this quite straightforward:
if (substrings.some(function(v) { return str.indexOf(v) >= 0; })) {
// There's at least one
}
Even better with an arrow function and the newish includes method (both ES2015+):
if (substrings.some(v => str.includes(v))) {
// There's at least one
}
Live Example:
const substrings = ["one", "two", "three"];
let str;
// Setup
console.log(`Substrings: ${substrings}`);
// Try it where we expect a match
str = "this has one";
if (substrings.some(v => str.includes(v))) {
console.log(`Match using "${str}"`);
} else {
console.log(`No match using "${str}"`);
}
// Try it where we DON'T expect a match
str = "this doesn't have any";
if (substrings.some(v => str.includes(v))) {
console.log(`Match using "${str}"`);
} else {
console.log(`No match using "${str}"`);
}
Regular expression
If you know the strings don't contain any of the characters that are special in regular expressions, then you can cheat a bit, like this:
if (new RegExp(substrings.join("|")).test(string)) {
// At least one match
}
...which creates a regular expression that's a series of alternations for the substrings you're looking for (e.g., one|two) and tests to see if there are matches for any of them, but if any of the substrings contains any characters that are special in regexes (*, [, etc.), you'd have to escape them first and you're better off just doing the boring loop instead. For info about escaping them, see this question's answers.
Live Example:
const substrings = ["one", "two", "three"];
let str;
// Setup
console.log(`Substrings: ${substrings}`);
// Try it where we expect a match
str = "this has one";
if (new RegExp(substrings.join("|")).test(str)) {
console.log(`Match using "${str}"`);
} else {
console.log(`No match using "${str}"`);
}
// Try it where we DON'T expect a match
str = "this doesn't have any";
if (new RegExp(substrings.join("|")).test(str)) {
console.log(`Match using "${str}"`);
} else {
console.log(`No match using "${str}"`);
}
Answer from T.J. Crowder on Stack OverflowThere's nothing built-in that will do that for you, you'll have to write a function for it, although it can be just a callback to the some array method.
Two approaches for you:
- Array
somemethod - Regular expression
Array some
The array some method (added in ES5) makes this quite straightforward:
if (substrings.some(function(v) { return str.indexOf(v) >= 0; })) {
// There's at least one
}
Even better with an arrow function and the newish includes method (both ES2015+):
if (substrings.some(v => str.includes(v))) {
// There's at least one
}
Live Example:
const substrings = ["one", "two", "three"];
let str;
// Setup
console.log(`Substrings: ${substrings}`);
// Try it where we expect a match
str = "this has one";
if (substrings.some(v => str.includes(v))) {
console.log(`Match using "${str}"`);
} else {
console.log(`No match using "${str}"`);
}
// Try it where we DON'T expect a match
str = "this doesn't have any";
if (substrings.some(v => str.includes(v))) {
console.log(`Match using "${str}"`);
} else {
console.log(`No match using "${str}"`);
}
Regular expression
If you know the strings don't contain any of the characters that are special in regular expressions, then you can cheat a bit, like this:
if (new RegExp(substrings.join("|")).test(string)) {
// At least one match
}
...which creates a regular expression that's a series of alternations for the substrings you're looking for (e.g., one|two) and tests to see if there are matches for any of them, but if any of the substrings contains any characters that are special in regexes (*, [, etc.), you'd have to escape them first and you're better off just doing the boring loop instead. For info about escaping them, see this question's answers.
Live Example:
const substrings = ["one", "two", "three"];
let str;
// Setup
console.log(`Substrings: ${substrings}`);
// Try it where we expect a match
str = "this has one";
if (new RegExp(substrings.join("|")).test(str)) {
console.log(`Match using "${str}"`);
} else {
console.log(`No match using "${str}"`);
}
// Try it where we DON'T expect a match
str = "this doesn't have any";
if (new RegExp(substrings.join("|")).test(str)) {
console.log(`Match using "${str}"`);
} else {
console.log(`No match using "${str}"`);
}
One line solution
substringsArray.some(substring=>yourBigString.includes(substring))
Returns true/false if substring exists/doesn't exist
Needs ES6 support
It can be as simple as that:
const arr = ['banana', 'monkey banana', 'apple', 'kiwi', 'orange'];
const checker = value =>
!['banana', 'apple'].some(element => value.includes(element));
console.log(arr.filter(checker));
ECMAScript 6 FTW!
The checker uses an arrow function.
The ! means that it will exclude all elements that doesn't meet the conditions.
The
some()method tests whether some element in the array passes the test implemented by the provided function.
from Array.prototype.some() docs on MDM
The
includes()method determines whether one string may be found within another string, returningtrueorfalseas appropriate.
from String.prototype.includes() docs on MDM
As some latest ECMAScript features aren't supported in all browsers, you should use Babel to compile your code to ECMAScript 5.
You can use some() function: to check if a string contains any element of an array.
e.g.
var fruitsArr = ['banana', 'monkey banana', 'apple', 'kiwi', 'orange'];
var myString = "I have an apple and a watermelon.";
var stringIncludesFruit = fruitsArr.some(fruit => myString.includes(fruit));
This function is pretty new. some() method accepts a callback where you define the condition you want to verify and it returns a boolean. Check the documentation at the link above.
Try this
const chars = [ '[', ']', '{', '}' ];
const str = "BlahBlah}";
const result = chars.some(x=>str.includes(x))
console.log(result)
ES6 automates looping through arrays with Array.prototype.some().
Try:
substrings.some(function(v) { return str.indexOf(v) >= 0; })
Or, to prototype this to String yourself (not recommend):
String.prototype.indexOfAny = function(arr) {
return arr.some(function(v) { return str.indexOf(v) >= 0; });
}
You can use Array.prototype.some, like this
if (chars.some(function(c) { return str.indexOf(c) !== -1; })) {
// Atleast one of the characters is present
};
Consider using regular expression:
var str = "Here is the string",
chars = ['z','g'];
// constructs the following regexp: /[zg]/
if (new RegExp("[" + chars.join('') + "]").test(str)) {
alert("Contains!");
}
Because includes will compare '#' with each array element.
Let's try with some or find if you want to find if you want to get exactly element
var array = ["123", "456", "#123"];
var el = array.find(a =>a.includes("#"));
console.log(el)
There appears to be multiple questions here since the title and post body differ. Do you want to know if the array has an element or do you want to get the element itself? If you want to get an element, which one(s) do you want--the first occurrence, the last occurrence or an array of all occurrences?
This post is intended as a resource for future visitors who might not necessarily want to find (i.e. return the first element from the start of the array that matches a predicate) as the top answer shows. To elaborate on that answer, there's a gotcha with indiscriminately replacing some with find in a boolean context--the element returned may be falsey as in
if ([5, 6, 0].find(e => e < 3)) { // fix: use `some` instead of `find`
console.log("you might expect this to run");
}
else {
console.log("but this actually runs " +
"because the found element happens to be falsey");
}
Note that e => e.includes("#") can be substituted with any predicate, so it's largely incidental to the question.
The same problem can occur when using indexOf in a condition and failing to account for the fact that 0 (the element was found at the first position in the array) is falsey.
Does any element match the predicate?
const array = ["123", "456", "#123"];
console.log(array.some(e => e.includes("#"))); // true
console.log(array.some(e => e.includes("foobar"))); // false
MDN: Array.prototype.some()
Does every element match the predicate?
const array = ["123", "456", "#123"];
console.log(array.every(e => e.includes("#"))); // false
console.log(array.every(e => /\d/.test(e))); // true
MDN: Array.prototype.every()
What is the first element that matches the predicate?
const array = ["123", "456", "#123", "456#"];
console.log(array.find(e => e.includes("#"))); // "#123"
console.log(array.find(e => e.includes("foobar"))); // undefined
MDN: Array.prototype.find()
What is the index of the first element that matches the predicate?
const array = ["123", "456", "#123", "456#"];
console.log(array.findIndex(e => e.includes("#"))); // 2
console.log(array.findIndex(e => e.includes("foobar"))); // -1
MDN: Array.prototype.findIndex()
What are all the elements that match the predicate?
const array = ["123", "456", "#123", "456#"];
console.log(array.filter(e => e.includes("#"))); // ["#123", "456#"]
console.log(array.filter(e => e.includes("foobar"))); // []
MDN: Array.prototype.filter()
What is the last element that matches the predicate?
const array = ["123", "456", "#123", "456#"];
console.log(array.findLast(e => e.includes("#"))); // "456#"
console.log(array.findLast(e => e.includes("foobar"))); // undefined
MDN: Array.prototype.findLast()
What is the index of the last element that matches the predicate?
const array = ["123", "456", "#123", "456#"];
console.log(array.findLastIndex(e => e.includes("#"))); // 3
console.log(array.findLastIndex(e => e.includes("foobar"))); // -1
MDN: Array.prototype.findLastIndex()
What are the indices of all of the elements that match the predicate?
const filterIndices = (a, pred) => a.reduce((acc, e, i) => {
pred(e, i, a) && acc.push(i);
return acc;
}, []);
const array = ["123", "456", "#123", "456#"];
console.log(filterIndices(array, e => e.includes("#"))); // [2, 3]
console.log(filterIndices(array, e => e.includes("foobar"))); // []
MDN: Array.prototype.reduce()
You could use this ES6 function:
function checkIfWordContainsLetters(wordToCheck, letters){
return !letters.reduce((a, b) => a.replace(b,''), wordToCheck.toLowerCase()).length;
}
console.log(checkIfWordContainsLetters("google", ["a","o","o","g","g","l","e","x"]));
console.log(checkIfWordContainsLetters("google", ["a","o","g","g","l","e","x"]));
The idea is to go through each letter in the letters array, and remove one (not more!) occurrence of it in the given wordToCheck argument (well, not exactly in it, but taking a copy that lacks that one character). If after making these removals there are still characters left over, the return value is false -- true otherwise.
Of course, if you use Internet Explorer, you won't have the necessary ES6 support. This is the ES5-compatible code:
function checkIfWordContainsLetters(wordToCheck, letters){
return !letters.reduce(function (a, b) {
return a.replace(b, '');
}, wordToCheck.toLowerCase()).length;
}
console.log(checkIfWordContainsLetters("google", ["a","o","o","g","g","l","e","x"]));
console.log(checkIfWordContainsLetters("google", ["a","o","g","g","l","e","x"]));
As long as it is not the best solution for long strings for which using some clever regex is definitely better, it works for short ones without whitespaces.
function checkIfWordContainsLetters(word, letters){
word = word.toLowerCase().split('');
for(var i = 0; i < letters.length; i++) {
var index = word.indexOf( letters[i].toLowerCase() );
if( index !== -1 ) {
// if word contains that letter, remove it
word.splice( index , 1 );
// if words length is 0, return true
if( !word.length ) return true;
}
}
return false;
}
checkIfWordContainsLetters("google", ["a","o","o","g","g","l","e","x"]); // returns true
checkIfWordContainsLetters("google", ["a","o","g","g","l","e","x"]); // returns false
There is an indexOf method that all arrays have (except Internet Explorer 8 and below) that will return the index of an element in the array, or -1 if it's not in the array:
if (yourArray.indexOf("someString") > -1) {
//In the array!
} else {
//Not in the array
}
If you need to support old IE browsers, you can polyfill this method using the code in the MDN article.
You can use the indexOfmethod and "extend" the Array class with the method contains like this:
Array.prototype.contains = function(element){
return this.indexOf(element) > -1;
};
with the following results:
["A", "B", "C"].contains("A") equals true
["A", "B", "C"].contains("D") equals false