Skip to content

Instantly share code, notes, and snippets.

@LeanSeverino1022
Created April 1, 2021 12:05
Show Gist options
  • Save LeanSeverino1022/badf5abdbd7818f06ff0f0058021fa56 to your computer and use it in GitHub Desktop.
Save LeanSeverino1022/badf5abdbd7818f06ff0f0058021fa56 to your computer and use it in GitHub Desktop.
Check if a string contains any item from a substring array #strings #vanillajs

Using some and includes

if (substrings.some(v => str.includes(v))) {
    // There's at least one
}

Example

var paragraph = "some things never change"; 
var substrings = ["random", "never", "test"];

if(substrings.some(s => paragraph.includes(s))) { 
	console.log("substring found")                 
} else {                     
	console.log("NOT FOUND");                 
}

output: substring found

Take not that The includes() method performs a case-sensitive search to determine whether one string may be found within another string, returning true or false as appropriate.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment