I want to use jQuery to highlight a character of a string on a webpage at an index of some value. The value is variable – one time it will be at the index of 2, and the ne
I want to use jQuery to highlight a character of a string on a webpage at an index of some value
To highlight characters by its index, Use the below snippet. This works on the already generated DOM. And all you need to get this working is a index.
$(function() {
var docText = $('#docContent').text();
var modifiedText = docText.highLightAt(7); //pass a index and that text will be highlighted.
$('#docContent').html(modifiedText);
//you can replace this 3 lines of code to single line like
// $('#docContent').html($('#docContent').text().highLightAt(7));
});
//define a highLightAt function to replace your char with a highlighted one.
String.prototype.highLightAt = function(index) {
return this.substr(0, index) + '' + this.substr(index,1) + '' + this.substr(index +1);
}
.highlight {
background-color: yellow;
color: green;
}
You random text goes here, And The program would highlight that particular character at a given index.
Note:
I have no idea how you are getting the index to highlight, You might end up giving index of a space character or you might not have total control over the index unless you are pretty sure of how you are generating it. So I feel playing with the characters should be easier and safe.
Additional Info
Previously I had built a similar stuff for a guy in SO. Here is the Working Jsfiddle. This must give you a basic idea. Below is a snippet you can look at if you are interested.
$(function(){
var docText = $('#docContent')[0].innerHTML;
var modifiedText = docText.replace(/e/g, "e"); //using regex to match all the chars `e`, We are not playing with the index, But only chars here
$('#docContent').html(modifiedText);
setInterval(function() {
$('span.highlight:not(.highlight-active):eq(0)').addClass('highlight-active');
}, 1000);
});
.highlight-active {
background-color: yellow;
color: green;
}
You random text goes here, And The program would highlight all the characters 'e' in this text.