Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wildcard string comparison in Javascript

People also ask

What are wildcards in Javascript?

A single character, such as an asterisk ( * ), is a wildcard character that can be read as several literal characters or an empty string. It is frequently used in file searches since it eliminates the need to input the complete name.

What is a wildcard string?

A wildcard search string consists of a word stem combined with special characters. The WILDCARD operator lets you define a wildcard search string, which can be used to locate related word matches in documents.

What is wildcard pattern matching?

A wildcard pattern is a series of characters that are matched against incoming character strings. You can use these patterns when you define pattern matching criteria. Matching is done strictly from left to right, one character or basic wildcard pattern at a time.


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:

  • RegExp "^, ., *, $"
  • string split("*")
  • array join(".*")
  • new RegExp(pattern[, flags])
  • RegExpObject.test(string)

You should use RegExp (they are awesome) an easy solution is:

if( /^bird/.test(animals[i]) ){
    // a bird :D
}

This function convert wildcard to regexp and make test (it supports . and * wildcharts)

function wildTest(wildcard, str) {
  let w = wildcard.replace(/[.+^${}()|[\]\\]/g, '\\$&'); // regexp escape 
  const re = new RegExp(`^${w.replace(/\*/g,'.*').replace(/\?/g,'.')}$`,'i');
  return re.test(str); // remove last 'i' above to have case sensitive
}

function wildTest(wildcard, str) {
  let w = wildcard.replace(/[.+^${}()|[\]\\]/g, '\\$&'); // regexp escape 
  const re = new RegExp(`^${w.replace(/\*/g,'.*').replace(/\?/g,'.')}$`,'i');
  return re.test(str); // remove last 'i' above to have case sensitive
}


// Example usage

let arr = ["birdBlue", "birdRed", "pig1z", "pig2z", "elephantBlua" ];

let resultA = arr.filter( x => wildTest('biRd*', x) );
let resultB = arr.filter( x => wildTest('p?g?z', x) );
let resultC = arr.filter( x => wildTest('*Blu?', x) );

console.log('biRd*',resultA);
console.log('p?g?z',resultB);
console.log('*Blu?',resultC);

You could use Javascript's substring method. For example:

var list = ["bird1", "bird2", "pig1"]

for (var i = 0; i < list.length; i++) {
  if (list[i].substring(0,4) == "bird") {
   console.log(list[i]);
  }
}

Which outputs:

bird1
bird2

Basically, you're checking each item in the array to see if the first four letters are 'bird'. This does assume that 'bird' will always be at the front of the string.


So let's say your getting a pathname from a URL :

Let's say your at bird1?=letsfly - you could use this code to check the URL:

var listOfUrls = [
                  "bird1?=letsfly",
                  "bird",
                  "pigs?=dontfly",
                 ]

for (var i = 0; i < list.length; i++) {
  if (listOfUrls[i].substring(0,4) === 'bird') {
    // do something
  }
}

The above would match the first to URL's, but not the third (not the pig). You could easily swap out url.substring(0,4) with a regex, or even another javascript method like .contains()


Using the .contains() method might be a little more secure. You won't need to know which part of the URL 'bird' is at. For instance:

var url = 'www.example.com/bird?=fly'

if (url.contains('bird')) {
  // this is true
  // do something
}