如何将数组项与文本进行匹配并使用找到的项(以文本格式设置并从数组列表中删除)?
我不知道数组,也不知道文本。但是当文本中包含数组项时,那就聚会吧!
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/