开发者

how to apply background color to the found text

hello i have following code and it works fine for finding and replacing string... but it is not working globally..how to make it to work as globally and after replacing i want to highlight that string into green color.. how..?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> New Document </title>
 <script type="text/javascript" src="../js/jquery-1.4.2.min.js"></script>
 <script>
$(document).ready(function(){
$('#replace').click(function(){
var oldstr=$('#inputstring').val();
var newstr=$('#newstring').val();
var para=$('#para').html();
var result=$('p:contains('+oldstr+')');


if(result)
{
var x=para.replace(new RegExp(oldstr, 'i','开发者_如何学Gog'), newstr);
$('#para').empty().html(x);

}
})
})
 </script>
 </head>

 <body>
  Enter the string to find:<input type="text" id="inputstring"><br>
  Enter string to replace:<input type="text" id="newstring"><br>
  <input type="button" value="Replace" id="replace"><br>
  <p id="para">This is the new paragraph written to test how to replace the a string  with desired string</p>
 </body>
</html>


$('body').html($('body').html().replace(oldstr, '<span style="color: green">' + newstr + '</span>'));


I think this is what you need to do:

if(result){
     var x=para.replace(new RegExp(oldstr, 'i','g'), newstr);
     $('#para').empty().html(x);
     $('#para').html($('#para').html().replace(oldstr, '<mark>' + newstr + '</mark>'));
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜