Link to home
Start Free TrialLog in
Avatar of Qsorb
QsorbFlag for United States of America

asked on

Highlight duplicates in lists over three characters in length

My html page highlights duplicates just fine but I need JavaScript to highlight only those words with 4 or more characters. I don't at all understand JavaScript, so best to show me where to change from 4 occurrences to whatever I need. This code currently displays ALL duplicates regardless of the length of the word, making pages with lots of text extremely difficult to read when highlighted. The code will be used on our closed network only and using MSIE or Firefox.

If possible, I'd prefer to have each duplicate occurrence counted and display the count with the duplicate, ordered with the most duplicates listed first. But if that's too difficult, I'll settle for the first part of this question.


<!DOCTYPE html>
<html>
<head>
  <script type='text/javascript' src='http://code.jquery.com/jquery-1.5.js'></script>
  
  <style type='text/css'>
    span.duplicate { background: #ffdddd;
		}
  </style>

<script type='text/javascript'>//<![CDATA[ 
$(function(){
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);

$('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;
});



});//]]>  

</script>
</head>
<body>

  <p>Bob is attempting to find the reason Janet is attempting to understand Bob and to reason with him.</p>
<hr />
<a class="words" href="#">Find duplicate words</a>
  
</body>
</html>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Khilu
Khilu
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Qsorb

ASKER

Yes, takes care of the count adjustment to be highlighted. Thanks!