-1

for example, there is following html in search results, and the aa is the keyword:

<body>
<div>
    <h2><a href="#aa">aabbcc</a></h2>
</div>
<div>
    <h2><a href="#bb">aaeeedd</a></h2>
</div>
<div>
    <h2><a href="#cc">vvaapp</a></h2>
</div>
</body>

I want to highlight the search keyword aa in results and don't change other anything : I try this:

var text = $('body').html().replace(new RegExp('aa','gim'),"<span class='highlight'>aa</span>");
$('body').html(text);

But all html were replaced, include the href '#aa'. I think use the each() and text() maybe ok. And is there better solution?

邱文强
  • 1
  • 1

4 Answers4

1

$('div a').each(function() {
  var text = $(this).text();
    $(this).text(text.replace('aa', 'bb')); 

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <div>
    <h2><a href="#aa">aabbcc</a></h2>
  </div>
  <div>
    <h2><a href="#bb">aaeeedd</a></h2>
  </div>
  <div>
    <h2><a href="#cc">vvaapp</a></h2>
  </div>
</body>

Using replace and .text()

$('div a').each(function() {
  var text = $(this).text();
    $(this).text(text.replace(/[aa]+/g, "bb")); 

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <div>
    <h2><a href="#aa">aabbcc</a></h2>
  </div>
  <div>
    <h2><a href="#bb">aaeeedd</a></h2>
  </div>
  <div>
    <h2><a href="#cc">vvaapp</a></h2>
  </div>
</body>

Using regex

guradio
  • 15,524
  • 4
  • 36
  • 57
0

$('#filter').on('keyup', function(event) {
  var keyword = event.currentTarget.value;
  highlight('a', keyword);
});

function highlight(selector, keyword) {
  $(selector).each(function(index, element) {
    var $element = $(element);
    var original = $element.data('originalText');
    if (original == undefined) {
      original = $element.html();
      $element.data('originalText', original);
    }
    $element.html(original.replace(keyword, '<span class="highlight">' + keyword + '</span>'));
  });
}
.highlight {
  background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <input type="text" id="filter"/>
  <div>
    <h2><a href="#aa">aabbcc</a></h2>
  </div>
  <div>
    <h2><a href="#bb">aaeeedd</a></h2>
  </div>
  <div>
    <h2><a href="#cc">vvaapp</a></h2>
  </div>
</body>
-1

Your best off using text.textContent() Its easier Remember you can still use Jquery and JS at once

-1

I found a function to solve it! And it is working well!

//highlight the search keyword
function highlight($area,keyword) {
    var re = new RegExp("(" + keyword + ")(?=[^<>]*<)","gi");
    var html = $area.html().replace(re, '<span class="searchkeyword">$1</span>');
    $area.html(html);
}

highlight($('body'), 'aa');
邱文强
  • 1
  • 1