c# .net Adsense ADO.NET Linq Viruses/security asp.net MVC JQuery Angular-js Node-js SEO Java C++ SQL API Networking vb.net .Net Css JavaScript Generics c#.Net entity framework HTML Website host Website Construction Guide HTTP tutorial W3C tutorial Web Services JSON Psychology Ionic framework Angular ReactJS Python Computer Android
JQuery

How to find repeated duplicated words in a paragraph using JQurey?

| | JQuery

In this article, I will show you find the repeated duplicated words in  a paragraph and apply css class using JQuery.  You can get all paragraphs using jQuery $(‘p’).text() and separated text by a space(‘ ’)  It will return a list of array string text. I used the following algorithm to find the duplicated words and apply css class (red color) for them.

    <script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            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(''));
        });
    </script>

    <style type="text/css">
        span.duplicate {
            background: red;
        }
    </style>
<body>
    <form id="form1" runat="server">
        <div style="border: 1px solid gray; width: 450px; height: 300px">
            <h2>document getelementsbyclassname example using JavaScript </h2>
            <p>Can't a guy call his mother pretty without it seemingstrange? Amen. I think that's one of Mom's little fibs, you know, like I'llsacrifice anything for my children.
She'salways got to wedge herself in the middle of us so that she can controleverything. Yeah. Mom's awesome. I run a pretty tight ship around here. With apool table.</p>
       </div>
    </form>
</body>      

Output: