Reputation: 7167
I want to highlight text in a specific position. Something like this: highlight with jquery, but it only highlights the word in the position n.
For instance, highlight only the second hello in the text "hello, hello, hello"
Thank you
Upvotes: 2
Views: 2647
Reputation: 630
Here's a way to do it, but it's not some concise and clever jQuery - mostly straight up javascript.
<div id="content">hello, hello, hello</div>
<script type="text/javascript">
$(document).ready(function() {
var searchKey = "hello"; // text to search for in element
var elementToSearch = $("#content"); // jquery element with text to search for matches
var instanceToHighlight = 2; // 1-based; e.g. 3 = third instance found
highlightText(searchKey, elementToSearch, instanceToHighlight);
});
function highlightText(searchKey, elementToSearch, instanceToHighlight) {
var content = elementToSearch.html();
var highlightIndex = instanceToHighlight - 1;
var lastIndex = -1;
var i = 0;
// get the index in the overall text of the instance to highlight
while (i <= highlightIndex) {
lastIndex = content.indexOf(searchKey, lastIndex + 1);
i++;
}
var testValue = content.slice(lastIndex, lastIndex + searchKey.length);
if (testValue !== searchKey) {
return; // didn't find an actual match
}
// chop up the content string so that the <span> tag can be wedged in around the text to highlight
var contentBeforeHighlightText = content.substr(0, lastIndex);
var contentAfterHighlightText = content.substr(lastIndex + searchKey.length, content.length - 1);
highlightedText = "<span class=\"highlight\">" + searchKey + "</span>";
content = contentBeforeHighlightText + highlightedText + contentAfterHighlightText;
elementToSearch.html(content);
}
</script>
Upvotes: 3