How to check if a string contains text from an array of substrings in JavaScript?
Solution 1
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}"`);
}
Solution 2
One line solution
substringsArray.some(substring=>yourBigString.includes(substring))
Returns true\false
if substring exists\does'nt exist
Needs ES6 support
Solution 3
var yourstring = 'tasty food'; // the string to check against
var substrings = ['foo','bar'],
length = substrings.length;
while(length--) {
if (yourstring.indexOf(substrings[length])!=-1) {
// one of the substrings is in yourstring
}
}
Solution 4
function containsAny(str, substrings) {
for (var i = 0; i != substrings.length; i++) {
var substring = substrings[i];
if (str.indexOf(substring) != - 1) {
return substring;
}
}
return null;
}
var result = containsAny("defg", ["ab", "cd", "ef"]);
console.log("String was found in substring " + result);
Solution 5
For people Googling,
The solid answer should be.
const substrings = ['connect', 'ready'];
const str = 'disconnect';
if (substrings.some(v => str === v)) {
// Will only return when the `str` is included in the `substrings`
}
Related videos on Youtube
PercivalMcGullicuddy
Updated on May 14, 2022Comments
-
PercivalMcGullicuddy almost 2 years
Pretty straight forward. In javascript, I need to check if a string contains any substrings held in an array.
-
Martin Hennings about 13 yearsIsn't there a
map()
function in the new HTML5-JavaScript-version? I remember having read something on that topic... -
T.J. Crowder about 13 years@Martin: Good point, not
map
so much assome
.some
would help, but you'd have to pass it a function.
-
-
kofifus over 6 yearsor shorter: if (substrings.some(v => v===str)) {
-
aamarks about 6 yearsYou kids...back when I was a kid we had to use these things called 'for' loops, and you had to use multiple lines and know whether your array was 1 or zero based, yeah...half the time you got it wrong and had to debug and look out for a little bugger called 'i'.
-
fcrick almost 6 yearsNote that this is an answer to a slightly different question, which asks if a string contains text from an array of substrings. This code checks if a string is one of the substrings. Depends on what is meant by "contains" I suppose.
-
Yunus Temurlenk about 4 yearsplease visit and check how to answer a question.
-
Arti about 4 years@YunusTemurlenk thnx
-
GreySage about 4 yearsYour first example doesn't need the
len
variable, just checki < arr.length
. -
Avatar almost 4 yearsPlus it returns the first occurence of the word in the string, which is very helpful. Not only a true/false.
-
Diyorbek Sadullaev almost 4 yearsLet's say we have a list of 100 substrings. Which way would be more efficient: RegExp or loop?
-
Abid Khairy almost 3 yearsthis is the cleanest answer here. many thanks!
-
Ridhwaan Shakeel almost 3 yearswhat is the es6 equivalent?
-
Justin Farrugia over 2 yearsthe only answer that returns the matched array string. this should have been included in previous example for completeness sake
-
Justin Farrugia over 2 yearsthe question here is not string in an array but strings in an array in a sentence