Highlight words

Discussion in 'JavaScript' started by shajimanjeri, Apr 23, 2007.

  1. #1
    Hey,

    I need to highlight some bad words in my div tag. How to highlight these words.
    For example
    Suppose this is my div tag with id 'newDiv'
    The content inside this div tag is
    "
    This world is filled with problems, It is becouse of ignorance.
    "
    Here I need to highlight these words "is, filled, ignorance",
    please give me a solution.

    with regards
    Shaji :)
     
    shajimanjeri, Apr 23, 2007 IP
  2. ajsa52

    ajsa52 Well-Known Member

    Messages:
    3,426
    Likes Received:
    125
    Best Answers:
    0
    Trophy Points:
    160
    #2
    You can use regular expressions and replace function. Example:

    
    <html>
    <head>
    
    <style type="text/css" media="screen">
    
    .ch { background-color:yellow; }
    
    </style>
    
    <script type="text/javascript">
    
    
    function change() 
    {
      var l_oldData = document.getElementById( "newDiv" ).innerHTML;
      var l_poner = '$1<span class="ch">$2</span>$3'; 
      var l_newData = l_oldData.replace( /(.*)(is)(.*)/gi, l_poner );
      l_oldData = l_newData.replace( /(.*)(filled)(.*)/gi, l_poner );
      l_newData = l_oldData.replace( /(.*)(ignorance)(.*)/gi, l_poner );
      // alert( "l_newData='" + l_newData + "'" );
      document.getElementById( "newDiv" ).innerHTML = l_newData;
    }
    
    </script>
    
    </head>
    <body onLoad="change();">
      <div id="oldDiv"> <!-- this div won't be changed -->
      This world is filled with problems, It is becouse of ignorance.
      </div>
      <div id="newDiv"> <!-- this div will be changed -->
      This world is filled with problems, It is becouse of ignorance.
      </div>
    </body>
    </html>
    
    
    Code (markup):
     
    ajsa52, Apr 23, 2007 IP