开发者

Highlighting text

开发者 https://www.devze.com 2023-02-19 04:17 出处:网络
I have to highlight the word passed in by the user. I use the below code to identify the presence of the word in a given sentence and then if present I di开发者_如何学Csplay the entire sentence.

I have to highlight the word passed in by the user. I use the below code to identify the presence of the word in a given sentence and then if present I di开发者_如何学Csplay the entire sentence.

<html>

Example

<style type="text/css">
  .highlight{
    color: maroon;
    font-size: 1.1em;
  }

</style>
<script type="text/javascript" src="../scripts/jquery-1.4.js"></script>
<script type="text/javascript">
function getSentence(word) {
var sentence="here is the text";
alert(word);
if (sentence.toLowerCase().indexOf(word.toLowerCase())!=-1) {
    sentence.replace(new RegExp('\b(word)\b', 'g'), '<span class="highlight">$1</span>');
    $("#placeholder").append("<h3>"+sentence+"</h3><br/>");

    }
    }
</script>

<form>
  <div>
    <a onclick=getSentence('text');>text</a>
  </div>
   <div id="placeholder"></div>
</form>

Please let me know how to highlight the given word in sentence.


sentence.replace(new RegExp('\b(word)\b', 'g'), '<span class="highlight">$1</span>');

This assumes your text has no HTML in it. If it does, we need to look for text nodes recursively and apply the regex.


May be you can try this as per your requirement

Highlight

0

精彩评论

暂无评论...
验证码 换一张
取 消