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:
Post your comments / questions
Recent Article
- ModuleNotFounEerror:No module named celery in Django Project
- How to get domain name information from a Domain using Python
- ModulenotFoundError: no module named 'debug_toolbar' -SOLUTION
- How to create superuser in django project hosted in cPanel without terminal
- CSS & images not loading in django admin | cpanel without terminal
- Could not build wheels for mysqlclient, which is required to install pyproject.toml-based projects
- How to sell domain name on Godaddy (2023)
- TemplateSyntaxError at / Could not parse the remainder: ' + 1' from 'forloop.counter0 + 1'
Related Article