简体   繁体   中英

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?

Here is how to write the regular expression for your question:

var txt = ...;
if (/^The .* dog eats$/.test(txt)) {
  ...
}

This matches your requirements

function contains(testString, subString){
    var subStringParts = subString.split("*");
    var testRegex = new RegExp(subStringParts.join(".*"));
    return testRegex.test(testString);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM