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

标签 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 的后续内容

最佳答案

尝试

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

关于javascript - jQuery:将数组项与文本匹配>从数组中删除项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21077399/

相关文章:

javascript - rails 。 jQuery 表单提交字段模糊

javascript - 如何在窗口调整大小时禁用和启用 ScrollMagic?

javascript - 在javascript中构建多维数组

javascript - Protractor - 比较 2 个数组的差异

javascript - AmCharts 4 - 多个数据集

javascript - 我们如何在 css 中为具有特殊字符的单词设置样式?

javascript - 快速傅立叶变换出错

javascript - 为什么我的 css3 动画在 JQuery 中不起作用?

javascript - 如何根据 json 属性在 Kendo jquery 下拉列表中设置默认值

c - 查找并打印带有空格或制表符分隔符的字符串的最后一个单词