Wildcard string comparison in Javascript
Solution 1:
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)
Solution 2:
You should use RegExp (they are awesome) an easy solution is:
if( /^bird/.test(animals[i]) ){
// a bird :D
}