简体   繁体   中英

text highlighting using javascript

I am trying to use a text highlight option using javascript.I know how to find the start postiion of the string, bt how do I make it highlight. my code looks like

<div id="entity">health insurance</div>
<div id="article">This kind of insurance is meant to supplement health insurance for cancer-care costs. But generally you're better off putting your money toward comprehensive health policies. </div>

and the javascript that I have used it

$(document).ready(function()
{
var test=document.getElementById('article').innerHTML;
var variable=document.getElementById('entity').innerHTML;
alert(test.search(new RegExp(variable, "i")));
});

This will alert the start postion of the string.

HTML:

<div id="entity">health insurance</div>
<div id="article">This kind of insurance is meant to supplement health insurance for cancer-care costs. But generally you're better off putting your money toward comprehensive health policies. </div>​

CSS:

.highlight {
  background-color: yellow
}

Javascript:

$(document).ready(function () {​
  var $test = $('#article');
  var entityText = $('#entity').html();
  var highlight = '<span class="highlight">' + entityText + '</span>';
  $test.html($test.html().replace(entityText, highlight));
}

Demo: http://jsfiddle.net/ehzPQ/2/

So, I'm just replacing the first occurrence of the 'entity' string with the same string wrapped up in a span class.

Did I understood your problem right?

-----------------------UPDATE-------------------------

If you want to highlight all the occurrences modify use a regular expression:

Updated Javascript:

$(document).ready(function () {
  var $test = $('#article');
  var entityText = $('#entity').html();
  var entityRegularExpression = new RegExp("\\b" + entityText + "\\b", "gi");
  var highlight = '<span class="highlight">' + entityText + '</span>';
  $test.html($test.html().replace(entityRegularExpression, highlight))
}

And updated demo: http://jsfiddle.net/ehzPQ/3/

Just replace yourDesireString with something like <span class='highlight'>yourDesireString</span> .

span.highlight {
     background-color: yellow;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM