Something like this works, if you ignore the need to escape the wildcard:
t = "I*have some bacon"
function wildCompare(string, search){
var prevIndex = -1,
array = search.split('*'), // Split the search string up in sections.
result = true;
for(var i = 0; i < array.length && result; i++){ // For each search section
var index = string.indexOf(array[i]); // Find the location of the current search section
if(index == -1 || index < prevIndex){ // If the section isn't found, or it's placed before the previous section...
return false;
}
}
return result;
}
Results:
wildCompare("Here, have some bacon", t) // False
wildCompare("I would like to have some bacon please", t) // True
wildCompare("I have some bacon", t)) // True
The easiest way to work around the "Wildcard escaping" thing would be to make the wildcard a variable character:
function wildCompare(string, search, wildcard){
var prevIndex = -1,
sa = search.split(wildcard),
// Etc
This way, you can specify what the wildcard character(s) are, allowing for a little more flexibility.
Disclaimer:
I'm sure there's plenty of reasons this code isn't "good", "efficient", or something like that, but it's a way it could be done. Also, it might return incorrect values in some cases.
mrfishie fixed the function for mutliple sequential wildcards:
function wildCompareNew(string, search) {
var startIndex = 0, array = search.split('*');
for (var i = 0; i < array.length; i++) {
var index = string.indexOf(array[i], startIndex);
if (index == -1) return false;
else startIndex = index;
}
return true;
}