Skip to content
Advertisement

Check if String Contains a Substring With “Catch All” Items

I’m looking to make a javascript function that can identify when a string contains a substring with a “catch all” item.
Example:

const contains = (string, substring) => ...

let string1 = "The blue dog eats."
let string2 = "The red dog eats."
let string3 = "The purple dog sleeps."

let substring = "The * dog eats"

// * is a catch all for any string
contains(string1, substring) // true
contains(string2, substring) // true
contains(string3, substring) // false

How would I go about making a function like this? Would I use regex for this?

Advertisement

Answer

This matches your requirements

function contains(testString, subString){
    var subStringParts = subString.split("*");
    var testRegex = new RegExp(subStringParts.join(".*"));
    return testRegex.test(testString);
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement