Created
July 31, 2016 16:51
-
-
Save roboncode/c7f91a4cb618d647c185e657b78e7f59 to your computer and use it in GitHub Desktop.
Match Rules
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// http://stackoverflow.com/questions/26246601/wildcard-string-comparison-in-javascript | |
// Short code | |
function matchRuleShort(str, rule) { | |
return new RegExp("^" + rule.split("*").join(".*") + "$").test(str); | |
} | |
// Explanation code | |
function matchRuleExpl(str, rule) { | |
// "." => Find a single character, except newline or line terminator | |
// ".*" => Matches any string that contains zero or more characters | |
rule = rule.split("*").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" | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment