Javascript/jQuery查找文本重复

Hus*_*ein 7 javascript jquery text duplicates

您将如何在文本文档中查找重复项.重复可以是一组连续的单词或句子.句子不必以点结尾.假设页面包含200行的文档,其中2个句子相同,我们希望在单击"检查重复按钮"时将这2个句子突出显示为重复.

pol*_*lau 5

有趣的问题 - 这是关于我如何做到这一点的想法:http://jsfiddle.net/SaQAs/1/无论如何都没有优化!

var text = $('p').text(),
    words = text.split(' '),
    sortedWords = words.slice(0).sort(),
    duplicateWords = [],
    sentences = text.split('.'),
    sortedSentences = sentences.slice(0).sort(),
    duplicateSentences = [];


for (var i=0; i<sortedWords.length-1; i++) {
    if (sortedWords[i+1] == sortedWords[i]) {
        duplicateWords.push(sortedWords[i]);
    }
}
duplicateWords = $.unique(duplicateWords);

for (var i=0; i<sortedSentences.length-1; i++) {
    if (sortedSentences[i+1] == sortedSentences[i]) {
        duplicateSentences.push(sortedSentences[i]);
    }
}
duplicateSentences = $.unique(duplicateSentences);

$('a.words').click(function(){
    var highlighted = $.map(words, function(word){
        if ($.inArray(word, duplicateWords) > -1)
            return '<span class="duplicate">' + word + '</span>';
        else return word;
    });
    $('p').html(highlighted.join(' '));
    return false;
});

$('a.sentences').click(function(){
    var highlighted = $.map(sentences, function(sentence){
        if ($.inArray(sentence, duplicateSentences) > -1)
            return '<span class="duplicate">' + sentence + '</span>';
        else return sentence;
    });
    $('p').html(highlighted.join('.'));
    return false;
});
Run Code Online (Sandbox Code Playgroud)

更新1

这个找到相同单词的序列:http://jsfiddle.net/YQdk5/1/从这里开始比较时,不应该很难忽略片段末尾的任何标点符号 - 你只需要编写自己的inArray方法版本.

var text = $('p').text(),
    words = text.split(' '),
    sortedWords = words.slice(0).sort(),
    duplicateWords = []
    highlighted = [];

for (var i=0; i<sortedWords.length-1; i++) {
    if (sortedWords[i+1] == sortedWords[i]) {
        duplicateWords.push(sortedWords[i]);
    }
}
duplicateWords = $.unique(duplicateWords);

for (var j=0, m=[]; j<words.length; j++) {
    m.push($.inArray(words[j], duplicateWords) > -1);
    if (!m[j] && m[j-1]) 
        highlighted.push('</span>');
    else if (m[j] && !m[j-1])
        highlighted.push('<span class="duplicate">');
    highlighted.push(words[j]);
}

$('p').html(highlighted.join(' '));
Run Code Online (Sandbox Code Playgroud)

更新2

我的正则表达式很弱,但这个(非常混乱!)版本似乎工作正常:http://jsfiddle.net/YQdk5/2/ - 我很确定可能有更好的方法来做到这一点,但是现在我必须不管它!:D - 祝你好运!

更新3

考虑到这一点,我认为之前更新的代码没有任何好处.这就是我删除它的原因.你仍然可以在这里找到它:http://jsfiddle.net/YQdk5/2/ 主要的一点是使用正则表达式匹配单词,类似于:

/^word(\.?)$/
Run Code Online (Sandbox Code Playgroud)