Wildcard string comparison in Javascript

I think you meant something like “*” (star) as a wildcard for example:

  • “a*b” => everything that starts with “a” and ends with “b”
  • “a*” => everything that starts with “a”
  • “*b” => everything that ends with “b”
  • “*a*” => everything that has an “a” in it
  • “*a*b*”=> everything that has an “a” in it, followed by anything, followed by a “b”, followed by anything

or in your example: “bird*” => everything that starts with bird

I had a similar problem and wrote a function with RegExp:

//Short code
function matchRuleShort(str, rule) {
  var escapeRegex = (str) => str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
  return new RegExp("^" + rule.split("*").map(escapeRegex).join(".*") + "$").test(str);
}

//Explanation code
function matchRuleExpl(str, rule) {
  // for this solution to work on any string, no matter what characters it has
  var escapeRegex = (str) => str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");

  // "."  => Find a single character, except newline or line terminator
  // ".*" => Matches any string that contains zero or more characters
  rule = rule.split("*").map(escapeRegex).join(".*");

  // "^"  => Matches any string with the following at the beginning of it
  // "$"  => Matches any string with that in front at the end of it
  rule = "^" + rule + "$"

  //Create a regular expression object for matching string
  var regex = new RegExp(rule);

  //Returns true if it finds a match, otherwise it returns false
  return regex.test(str);
}

//Examples
alert(
    "1. " + matchRuleShort("bird123", "bird*") + "\n" +
    "2. " + matchRuleShort("123bird", "*bird") + "\n" +
    "3. " + matchRuleShort("123bird123", "*bird*") + "\n" +
    "4. " + matchRuleShort("bird123bird", "bird*bird") + "\n" +
    "5. " + matchRuleShort("123bird123bird123", "*bird*bird*") + "\n" +
    "6. " + matchRuleShort("s[pe]c 3 re$ex 6 cha^rs", "s[pe]c*re$ex*cha^rs") + "\n" +
    "7. " + matchRuleShort("should not match", "should noo*oot match") + "\n"
);

If you want to read more about the used functions:

Leave a Comment