3

I have an input with type text which then I perform a click and the matcher text will be highlighted. The highlighted works but for every paragraph it is adding a new paragraph with the same text. Here you can find a jsfiddle which I have created and maybe it will help in my problem

$(document).ready(function() {
  $("#searchButton").click(function() {
    searchHighlight($("#search").val());
  });
});

function searchHighlight(searchText) {
  if (searchText) {
    var searchExp = new RegExp(searchText, "ig");
    var content = $('p').text();
    var matches = content.match(searchExp);
    if (matches) {
      $('p').html(content.replace(searchExp, function(match) {
        return "<span class='highlight'>" + match + "</span>";
      }));
    } else {
      $(".highlight").removeClass(".highlight");
    }
  } else {
    $(".highlight").removeClass(".highlight");
  }
}
.highlight {
  background: yellow;
  font-weight: bold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <form class="form-inline">
    <label class="sr-only" for="search">Search</label>
    <div class="input-group">
      <input id="search" type="text" class="form-control" placeholder="Highlight in text">
      <span class="input-group-btn">
        <button class="btn btn-secondary" id="searchButton" onclick="selectText()" type="button">Search</button>
      </span>
    </div>
  </form>
  <div class="search-content" id="search-content">
    <h2>Perceived end knowledge certainly day sweetness why cordially</h2>
    <p>As collected deficient objection by it discovery sincerity curiosity. Quiet decay who round three world whole has mrs man. Built the china there tried jokes which gay why. Assure in adieus wicket it is. But spoke round point and one joy. Offending her moonlight men sweetness see unwilling. Often of it tears whole oh balls share an.</p>
    <p>Unpacked reserved sir offering <strong>bed judgment may and quitting speaking</strong>. Is do be improved raptures offering required in replying raillery. Stairs ladies friend by in mutual an no. Mr hence chief he cause. Whole no doors on hoped. Mile tell if help they ye full name.</p>
    <p>Behaviour we improving at something to. Evil true high lady roof men had open. To <b class="bold">projection</b> considered it precaution an melancholy or. Wound young you thing worse along being ham. Dissimilar of favourable solicitude if sympathize middletons at. Forfeited up if disposing perfectly in an eagerness perceived necessary. Belonging sir curiosity discovery extremity yet forfeited prevailed own off. Travelling by introduced of mr terminated. Knew as miss my high hope quit. In curiosity shameless dependent knowledge up.</p>
    <p>Sudden she seeing garret far regard. <strike>By hardly it direct if pretty up regret</strike>. Ability thought enquire settled prudent you sir. Or easy knew sold on well come year. Something consulted age extremely end procuring. Collecting preference he inquietude projection me in by. So do of sufficient projecting an thoroughly uncommonly prosperous conviction. Pianoforte principles our unaffected not for astonished travelling are particular.</p>
    <p>Situation admitting promotion at or to perceived be. Mr acuteness we as estimable enjoyment up. An held late as felt know. Learn do allow solid to grave. Middleton suspicion age her attention. Chiefly several bed its wishing. Is so moments on chamber pressed to. Doubtful yet way properly answered humanity its desirous. Minuter believe service arrived civilly add all. Acuteness allowance an at eagerness favourite in extensive exquisite ye.</p>
    <p>Started his hearted any civilly. So me by marianne admitted speaking. Men bred fine call ask. Cease one miles truth day above seven. Suspicion sportsmen provision suffering mrs saw engrossed something. Snug soon he on plan in be dine some.</p>
    <p>Husbands ask repeated resolved but laughter debating. She end cordial visitor noisier fat subject general picture. Or if offering confined entrance no. Nay rapturous him see something residence. Highly talked do so vulgar. Her use behaved spirits and natural attempt say feeling. Exquisite mr incommode immediate he something ourselves it of. Law conduct yet chiefly beloved examine village proceed.
    </p>
    <p>Compliment interested discretion estimating on stimulated apartments oh. Dear so sing when in find read of call. As distrusts behaviour abilities defective is. Never at water me might. On formed merits hunted unable merely by mr whence or. Possession the unpleasing simplicity her uncommonly.</p>
    <p>The him father parish looked has sooner. Attachment frequently gay terminated son. You greater nay use prudent placing. Passage to so distant behaved natural between do talking. Friends off her windows painful. Still gay event you being think nay for. In three if aware he point it. Effects warrant me by no on feeling settled resolve.</p>
  </div>
</div>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
TheCoderGuy
  • 771
  • 6
  • 24
  • 51

2 Answers2

4

Because you want to keep the existing HTML structure, you should probably replace the .html() of the entire .search-content.

Because you probably don't want to keep highlighted sections from a prior click, you might call $(".highlight").removeClass("highlight"); every time, at the beginning of the function.

removeClass accepts a class name, not a selector string, so .removeClass(".highlight"); should be .removeClass("highlight");.

Though, it might be better to use .replaceWith to remove the new <span>s entirely - that way, you're left with just text nodes before replacement starts again.

Because the string to search for may contain characters with a special meaning in a regular expression, best to escape them first before constructing the pattern. (otherwise, for example, searches for foo. will match both fooB and foo., because . matches any character)

const escape = s => s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');

$("#searchButton").click(function() {
  searchHighlight($("#search").val());
});

function searchHighlight(searchText) {
  $(".highlight").replaceWith(function() {
    return $(this).text();
  });
  if (!searchText) {
    return;
  }
  var searchExp = new RegExp(escape(searchText), "ig");
  $('.search-content').html(
    $('.search-content').html().replace(
      searchExp,
      function(match) { return "<span class='highlight'>" + match + "</span>"; }
    )
  );
}
.highlight {
  background: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <form class="form-inline">
    <label class="sr-only" for="search">Search</label>
    <div class="input-group">
      <input id="search" type="text" class="form-control" placeholder="Highlight in text">
      <span class="input-group-btn">
         <button class="btn btn-secondary" id="searchButton" type="button">Search</button>
       </span>
    </div>
  </form>

  <div class="search-content" id="search-content">

    <h2>Perceived end knowledge certainly day sweetness why cordially</h2>

    <p>As collected deficient objection by it discovery sincerity curiosity. Quiet decay who round three world whole has mrs man. Built the china there tried jokes which gay why. Assure in adieus wicket it is. But spoke round point and one joy. Offending
      her moonlight men sweetness see unwilling. Often of it tears whole oh balls share an.</p>

    <p>Unpacked reserved sir offering <strong>bed judgment may and quitting speaking</strong>. Is do be improved raptures offering required in replying raillery. Stairs ladies friend by in mutual an no. Mr hence chief he cause. Whole no doors on hoped. Mile
      tell if help they ye full name.</p>

    <p>Behaviour we improving at something to. Evil true high lady roof men had open. To
      <b class="bold">projection</b> considered it precaution an melancholy or. Wound young you thing worse along being ham. Dissimilar of favourable solicitude if sympathize middletons at. Forfeited up if disposing perfectly in an eagerness perceived
      necessary. Belonging sir curiosity discovery extremity yet forfeited prevailed own off. Travelling by introduced of mr terminated. Knew as miss my high hope quit. In curiosity shameless dependent knowledge up.</p>

    <p>Sudden she seeing garret far regard. <strike>By hardly it direct if pretty up regret</strike>. Ability thought enquire settled prudent you sir. Or easy knew sold on well come year. Something consulted age extremely end procuring. Collecting preference
      he inquietude projection me in by. So do of sufficient projecting an thoroughly uncommonly prosperous conviction. Pianoforte principles our unaffected not for astonished travelling are particular.</p>

    <p>Situation admitting promotion at or to perceived be. Mr acuteness we as estimable enjoyment up. An held late as felt know. Learn do allow solid to grave. Middleton suspicion age her attention. Chiefly several bed its wishing. Is so moments on chamber
      pressed to. Doubtful yet way properly answered humanity its desirous. Minuter believe service arrived civilly add all. Acuteness allowance an at eagerness favourite in extensive exquisite ye.</p>

    <p>Started his hearted any civilly. So me by marianne admitted speaking. Men bred fine call ask. Cease one miles truth day above seven. Suspicion sportsmen provision suffering mrs saw engrossed something. Snug soon he on plan in be dine some.</p>

    <p>Husbands ask repeated resolved but laughter debating. She end cordial visitor noisier fat subject general picture. Or if offering confined entrance no. Nay rapturous him see something residence. Highly talked do so vulgar. Her use behaved spirits
      and natural attempt say feeling. Exquisite mr incommode immediate he something ourselves it of. Law conduct yet chiefly beloved examine village proceed.
    </p>

    <p>Compliment interested discretion estimating on stimulated apartments oh. Dear so sing when in find read of call. As distrusts behaviour abilities defective is. Never at water me might. On formed merits hunted unable merely by mr whence or. Possession
      the unpleasing simplicity her uncommonly.</p>

    <p>The him father parish looked has sooner. Attachment frequently gay terminated son. You greater nay use prudent placing. Passage to so distant behaved natural between do talking. Friends off her windows painful. Still gay event you being think nay
      for. In three if aware he point it. Effects warrant me by no on feeling settled resolve.</p>
  </div>
</div>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Arrow function it is not allowed it is coming error expression excepted. – TheCoderGuy Sep 24 '19 at 08:51
  • Edited, but probably best to upgrade your IDE - arrow functions are a great way of making code terse and more readable, and are quite old (they're ES2015, and it's 2019 now). Use [Babel](https://babeljs.io) to transpile code to ES5 automatically for production, to support obsolete browsers. (ES5 is generally ugly compared to ES6+) – CertainPerformance Sep 24 '19 at 08:54
  • @CertainPerfomance Yes I know I use always the es6+ but in this project they work with es5. – TheCoderGuy Sep 24 '19 at 08:58
  • ES6 already works just fine in combination with jQuery - press "Run code snippet" in the answer to see it working. jQuery is written in Javascript, and ES6 is Javascript syntax too. – CertainPerformance Sep 24 '19 at 09:04
0

That is because you are replacing the content for every P tag in your if statement, I have modified your code to search within your div and called the html() instead of text() to keep formatting as is

  function searchHighlight(searchText) {
        if (searchText) {
            var searchExp = new RegExp(searchText, "ig");
            var content = $('#search-content').html();             
            var matches = content.match(searchExp);
            if (matches) {
                $('#search-content').html(content.replace(searchExp, function(match) {
                    return "<span class='highlight'>" + match + "</span>";
                }));
            } else {
                $(".highlight").removeClass(".highlight");
            }
        } else {
            $(".highlight").removeClass(".highlight");

        }


    }