jQuery:将数组项与文本匹配>从数组中删除项目

时间:2014-01-12 16:49:55

标签: javascript jquery arrays match

如何将数组项与文本匹配并使用找到的项目(文本格式和从数组列表中删除)?

我不知道数组,我不知道文字。但是当文本中包含一个数组项时,就可以参加派对了!

var arrString = 'apple, banana, monkey, sugar',
    text = "This a nice  monkey  zoo with  banana  trees.";

var arr = arrString.split(", ");

var arrMatch = "";

for(var i=0;i<arr.length;i++){
    if(text.search(arr[i])!=-1){
        arrMatch = arr[i];

        //format found item in text
        var text = text.replace(arrMatch, '<b>'+arrMatch+'</b>');

        //Remove found item from array <<<<<< Needs a fix
        if ( i !== -1 ) arr.splice(i, 1);
    }
}

if(arrMatch !== "") {
    $("body").append(arrString + '<br><br>The text contains the array item(s) "'+ arrMatch +'".');
}

var arrLeft = arr.join(", ");

$("body").append("<br><br><hr /><br>" + text + "<br><br>These array items are left: " + arrLeft);

测试:http://jsfiddle.net/Hxdht/3/

注意:这是jQuery: Find array items in text string

的后续行动

2 个答案:

答案 0 :(得分:1)

尝试

for(var i=0;i<arr.length;i++){
    if(text.search(arr[i])!=-1){
        arrMatch = arr[i];
        text = text.replace(arrMatch, '<b>'+arrMatch+'</b>'); 
        //Remove found item from array <<<<<< Needs a fix
        if ( i !== -1 ){ arr.splice(i, 1); i--;}//decrement the index
    }
}

JSFiddle here

答案 1 :(得分:1)

另一种技术( Fiddle ):

var arrString = "apple, banana, monkey, sugar",
    text = "This a nice  monkey  zoo with  banana  trees.";

var arr = arrString.split(", ");

var found = [], foundIndices = [];
var test = new RegExp("\\b" + arr.join("\\b|\\b") + "\\b", "g");

var newText = text.replace(test, function(word) {
    if (found.indexOf(word) < 0) {
        found.push(word);
    };
    var index = arr.indexOf(word);
    if (foundIndices.indexOf(index) < 0) {
        foundIndices.push(index);
    }
    return "<b>" + word + "</b>";
});

foundIndices.sort(function(a, b) {return b - a;});
foundIndices.forEach(function(index) {arr.splice(index, 1);});

log(arrString);
log("The text contains " + found.join(", ") + ".");
log(newText);
log("These array itmes are left: " + arr.join(", ") + ".");

如果要测试的项目在正则表达式中具有重要的特殊字符,则无效。

最大的区别在于它构建了一个正则表达式,然后一次性完成所有匹配的字符串。