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
- How to add two numbers in Android Studio? | Source Code
- FindViewByID returns null in android studio -SOLVED
- Saving changes is not permitted in SQL SERVER - [SOLVED]
- Restore of database failed. File cannot be restored over the existing. -[SOLVED]
- One or more projects in the solution were not loaded correctly in Visual Studio 2019 | FIXED
- How to find Laptop's Battery Health?
- SOLVED-Related Field got invalid lookup: icontains error in Django
- How to enable Search Feature in Django admin?
Related Article