Reputation:
I defined some tags in an array:
var myArray = [
"mouse",
"common",
"malcom",
"mountain",
"melon",
"table"
];
Now I want to extract my defined tags from a string, for example
from the string: the mouse is on the desk
, I want to extract the "mouse" tag
or from the string the mouse is on the table
, I want to extract the tags "mouse" and "table"
This code partially works, but there is some problem:
var myArray = [
"mouse",
"common",
"malcom",
"mountain",
"melon",
"table"
];
Object.defineProperty(Array.prototype, "MatchInArray", {
enumerable: false,
value: function(value) {
return this.filter(function(currentItem) {
return currentItem.match(value);
});
}
});
function doSearch(text){
out = myArray.filter(function(currentItem){
return currentItem.toLowerCase().indexOf(text) !== -1;
});
return out;
}
myInput.oninput = function(){
var XXX = this.value;
var YYY = XXX.replace(/ /g,',');
var ZZZ = YYY.split(',');
for(var i=0; i<ZZZ.length; i++){
output.innerHTML = doSearch(ZZZ[i]);
}
//output.innerHTML = doSearch(this.value);
};
What I'm doing wrong?
Upvotes: 2
Views: 47
Reputation: 20211
Flip the comparison of text to item so that you don't have to do all that regex and splitting:
function doSearch(text){
out = myArray.filter(function(currentItem){
return text.toLowerCase().indexOf(currentItem) !== -1;
});
return out;
}
myInput.oninput = function(){
output.innerHTML = doSearch(this.value);
};
Upvotes: 1