使用jQuery删除项目列表中的重复单词

时间:2011-11-11 20:35:02

标签: jquery

我有一个包含许多项目的列表,其中包含一些我要删除或隐藏的重复文本。所以从这个:

<ul class="juicy">
<li>Juicy Green Apples</li>
<li>Juicy Green Tomatoes</li>
<li>Juicy Green Broccoli</li>
</ul>

我想实现这个目标:

<ul class="juicy">
<li>Apples</li>
<li>Tomatoes</li>
<li>Broccoli</li>
</ul>

2 个答案:

答案 0 :(得分:1)

如果您要替换的文本事先已知,jQuery的.text()方法可以很容易地处理这个问题。

var textToReplace = "Juicy Green",
    re = new RegExp(textToReplace,"i");
$(".juicy li").text(function(index,text){
  return text.replace(re,'');
});

编辑:在评论中回答问题:

这样的事情:

var textToReplaceArr = ["Juicy Green","Sour Yellow"];
for (var i = 0; i < textToReplaceArr.length; i++) {
  $(".juicy li").text(function(index,text){
    var re = new RegExp(textToReplaceArr[i],"i");
    return text.replace(re,'');
  });
}

答案 1 :(得分:0)

你想尝试一些动态的东西吗?

$(document).ready(

function() {
    var repeatedWordsArray = new Array();
    var wordsToRemoveArray = new Array();
    var i = 0;
    $($("ul.juicy > li").map(function() {
        return $(this).text();
    }).get().join(" ").split(/\s+/g)).each(   //Joins the text of all elements, appends space between them and then splits with space character

    function() {
        repeatedWordsArray[this] = repeatedWordsArray[this] == undefined ? 1 : repeatedWordsArray[this] + 1;      //Increments the counter when the same word is encountered
        if (repeatedWordsArray[this] == 2) {     //If found twice, make a note of the word
            wordsToRemoveArray[i++] = this;
        }
    });
    if (wordsToRemoveArray.length > 0) {
        $("ul.juicy > li").each(
        function() {
            var ulElement = this;
            $(wordsToRemoveArray).each(
                function() {
                    var regexp = new RegExp('^\\s*\\w+\\s*$');
                    if(!$(ulElement).text().match(regexp)) {     //Do not match if the text of element contains a single word with or without spaces at its ends
                        regexp = new RegExp('\\s*' + this + '\\s*','g');
                        $(ulElement).text($(ulElement).text().replace(regexp, ''));   //Set the text of the element after removing the repeatedly found word
                    }
                }
                );
            }
        );
    }
}
);

这也适用于以下ul:

<ul class="juicy">
    <li>Juicy Green Apples</li>
    <li>Juicy Green Tomatoes</li>
    <li>Juicy Green Broccoli</li>
    <li>Juicy</li>
    <li>      Green  </li>
 </ul>