我在数组中定义了一些标签:
var myArray = [
"mouse",
"common",
"malcom",
"mountain",
"melon",
"table"
];
现在我想从字符串中提取我定义的标签,例如
来自字符串:the mouse is on the desk
,我想提取“鼠标”标签
或从字符串the mouse is on the table
,我想提取标签“鼠标”和“表格”
此代码部分有效,但存在一些问题:
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);
};
我做错了什么?
答案 0 :(得分:1)
翻转文本与项目的比较,以便您不必执行所有正则表达式和拆分:
function doSearch(text){
out = myArray.filter(function(currentItem){
return text.toLowerCase().indexOf(currentItem) !== -1;
});
return out;
}
myInput.oninput = function(){
output.innerHTML = doSearch(this.value);
};