JSFiddle - React, Tailwind, and code Playground
by ericbarnard
HTML
<input id="term" type="text" />
<button id="search">Search</button>
<div id="output">
</div>
JavaScript
var tests = [
"F102B",
"F108CPL",
"F111B",
"F112BX",
"F113B",
"F114B",
"F125BR",
"F136BR",
"F35BR",
"F36BRX",
"F37BR",
"F41BR",
"XM1190BL",
"MS004",
"MS005",
"MS006",
"MS009",
"MS014",
"MS030",
"CAPTAIN/SBRNZ"
];
var wildcard = "*";
$('#search').click(function(){
$('#output').empty();
var term = $('#term').val();
if(!term){
return;
}
var results = performSearch(term);
if(results && results.length){
$.each(results, function(i, item){
$('#output').append("<p>" + item + "</p>");
});
}
});
var performSearch = function(filterStr){
var replacer = "";
//escape any wierd characters they might using
filterStr = filterStr.replace(/\\/g, "\\");
// build our replacer regex
if(wildcard === "*"){
replacer = /\*/g;
}else{
replacer = /\%/g;
}
//first replace all % percent signs with the true regex wildcard *
var regexStr = filterStr.replace(replacer, "[^\']*");
//ensure that we do "beginsWith" logic
regexStr = "^" + regexStr;
// then create an actual regex object
regex = new RegExp(regexStr, "gi");
var keepers = [];
$.each(tests, function(i, itemStr){
if(itemStr.match(regex)){
keepers.push(itemStr);
}
});
return keepers;
};