我在数组中定义了一些标签:
var myArray = [
"mouse",
"common",
"malcom",
"mountain",
"melon",
"table"
];
现在我想从字符串中提取我定义的标签,例如
从字符串:the mouse is on the desk
,我想提取“mouse”标签
或者从字符串 the mouse is on the table
中,我想提取标签 "mouse" 和 "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);
};
我做错了什么?
最佳答案
翻转文本与项目的比较,这样你就不必做所有的正则表达式和拆分:
function doSearch(text){
out = myArray.filter(function(currentItem){
return text.toLowerCase().indexOf(currentItem) !== -1;
});
return out;
}
myInput.oninput = function(){
output.innerHTML = doSearch(this.value);
};
关于javascript - 匹配字符串中存在的定义标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27365218/