我会使用这个设置:
var suggestions = [
"the dog",
"the cat",
"he went then",
"boat engine",
"another either thing",
"some string the whatever"
];
function filterWord(arr, filter) {
var i = arr.length, cur,
re = new RegExp("\\b" + filter + "\\b");
while (i--) {
cur = arr[i];
if (re.test(cur)) {
arr.splice(i, 1);
}
}
}
filterWord(suggestions, "the");
console.log(suggestions);
演示:http: //jsfiddle.net/Kacju/
它向后循环,正确检查要查找的单词(通过使用\b
标识符作为单词边界),并删除任何匹配项。
如果要生成包含匹配项的新数组,请正常循环,并且只push
对新数组的任何不匹配项进行循环。你可以使用这个:
var suggestions = [
"the dog",
"the cat",
"he went then",
"boat engine",
"another either thing",
"some string the whatever"
];
function filterWord(arr, filter) {
var i, j, cur, ret = [],
re = new RegExp("\\b" + filter + "\\b");
for (i = 0, j = arr.length; i < j; i++) {
cur = arr[i];
if (!re.test(cur)) {
ret.push(cur);
}
}
return ret;
}
var newSuggestions = filterWord(suggestions, "the");
console.log(newSuggestions);
演示:http: //jsfiddle.net/Kacju/1/