Reputation: 423
I am working to search file names using wildcard characters (* %.) i.e the user will type in the expression and script would run the user input pattern on the filenames residing in predefined directory.I tried to do it in javascript, but facing issues. I am new to javascript, so do not know whether it is the best way to do it. Here is the snippet of code I tried:
<script>
function checkPattern(str1)
{
var matchesFound = new Array();
for(var i=0; i<directory.length;i++)
{
var newStr1 = directory[i];
if(newStr1 == newStr1.match(str1))
matchesFound.push(newStr);
}
//display items in matchesFound
}
</script>
</head>
<body>
<form>
<input name="testText" type="text" size=45>
<button onClick="checkPattern(testText.value);">Check pattern</button>
</form>
</body>
Upvotes: 0
Views: 2633
Reputation: 43673
Let's use SQL syntax (%
wildcard).
To convert such seach string into regex pattern use something like this »
RegExp.quote = function(str) {
return (str+'').replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
};
var replaceCallback = function(match) {
return RegExp.quote(match);
}
regexPattern = searchString.replace(/[^%]+/g, replaceCallback).replace(/%/g, ".*");
Test it here.
Then you can use such regex pattern with RegExp
- read this.
Upvotes: 1
Reputation: 207511
You need to convert those wildcard characters into valid regular expressions. Right now you are trying to match a string and against another string.
Upvotes: 0