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 some method
  • 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 Overflow
Top answer
1 of 16
493

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 some method
  • 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}"`);
}

2 of 16
138

One line solution

substringsArray.some(substring=>yourBigString.includes(substring))

Returns true/false if substring exists/doesn't exist

Needs ES6 support

๐ŸŒ
Sentry
sentry.io โ€บ sentry answers โ€บ javascript โ€บ how to check whether a string contains a substring in javascript?
How to Check Whether a String Contains a Substring in JavaScript? | Sentry
You can use JavaScriptโ€™s includes() method to check whether a string contains a substring. This will return true if the substring is found, or false if not.
Top answer
1 of 5
78

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)

2 of 5
18

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()

๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Global_Objects โ€บ String โ€บ includes
String.prototype.includes() - JavaScript | MDN
All values that are not regexes are coerced to strings, so omitting it or passing undefined causes includes() to search for the string "undefined", which is rarely what you want.
๐ŸŒ
SamanthaMing
samanthaming.com โ€บ tidbits โ€บ 28-check-if-string-contains-substring
Checking if String contains Substring | SamanthaMing.com
It will either true or false. const weather = ['sun', 'rain', 'cloudy']; weather.includes('sun'); // true ยท If you're checking if a node is a descendant of a specified node, you can use the contains() method.
Find elsewhere
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ how-to-find-if-an-array-contains-a-specific-string-in-javascript-jquery
How to find if an array contains a specific string in JavaScript/jQuery ? | GeeksforGeeks
July 31, 2024 - Here are the different methods to check if the string contains only digits.1. Using Regular Expression (RegExp) with test() MethodThe most efficient way to check if a string co ...
Top answer
1 of 2
3

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"]));

2 of 2
1

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
๐ŸŒ
W3Schools
w3schools.com โ€บ jsref โ€บ jsref_includes_array.asp
JavaScript Array includes() Method
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST ... Array[ ] Array( ) at() concat() constructor copyWithin() entries() every() fill() filter() find() findIndex() findLast() findLastIndex() flat() flatMap() forEach() from() includes() indexOf() isArray() join() keys() lastIndexOf() length map() of() pop() prototype push() reduce() reduceRight() rest (...) reverse() shift() slice() some() sort() splice() spread (...) toReversed() toSorted() toSpliced() toString() unshift() values() valueOf() with() JS Boolean
๐ŸŒ
Love2Dev
love2dev.com โ€บ blog โ€บ javascript-includes
JavaScript Includes To Search ๐Ÿ” In Strings & Arrays
The JavaScript ๐Ÿ‘จโ€๐Ÿ’ป includes method finds ๐Ÿ” the target in an Array or String. Learn how to search arrays and strings to determine if they contain your item.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ javascript-program-to-check-if-a-string-contains-any-special-character
JavaScript Program to Check if a String Contains any Special Character | GeeksforGeeks
June 3, 2024 - Given string is : Geeks@forGeeks String contain a special character. In this method, we will create an array of special characters and use the some method to check if any character in the given string is present in the array of special characters.
๐ŸŒ
Sololearn
sololearn.com โ€บ en โ€บ Discuss โ€บ 2356405 โ€บ solvedhow-can-i-test-if-a-string-contains-some-characters-that-are-in-a-variable-without-a-specified-order
[SOLVED]How can I test if a string contains some characters [that are in a variable] without a specified order? | Sololearn: Learn to code for FREE!
Simple contains is not an option for you? Otherwise you'd have to define the substring as a pattern and then match it. ... I don't think it's possible to check the existence of all characters from a given substring in another string independent from their order. Therefore I would create an array of characters from the substring and check each entry in a loop.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ check-if-an-item-is-in-an-array-in-javascript-js-contains-with-array-includes
Check if an Item is in an Array in JavaScript โ€“ JS Contains with Array.includes()
June 28, 2022 - The substring "web" doesn't exist in the string so false gets returned. In this article, we talked about the includes() method in JavaScript. You use it to check if an item exists in an array.
๐ŸŒ
Quora
quora.com โ€บ How-can-I-check-if-one-string-contains-another-substring-in-JavaScript
How to check if one string contains another substring in JavaScript - Quora
Answer (1 of 2): ES6 introduced String.prototype.includes: [code]var string = "foo", substring = "oo"; string.includes(substring) [/code][code ]includes[/code] doesnโ€™t have IE support, though. In an ES5 or older environment, String.prototype.indexOf, which returns โˆ’1 when it doesnโ€™t find ...
๐ŸŒ
JavaScript in Plain English
javascript.plainenglish.io โ€บ javascript-check-if-string-contains-character-1f6b77394ca5
How to Check if a String Contains a Character in JavaScript | JavaScript in Plain English
June 17, 2022 - The includes() method returns true if the string contains the character, and false if it doesn't. const str = 'Bread and Milk';const char1 = 'd'; const char2 = 'p';console.log(str.includes(char1)); // trueconsole.log(str.includes(char2)); // ...