0

I want to highlight the word which user has searched. I am getting an array in response which will shows the occurrence of that word. I want to highlight that word inside my array which I received.

 success:function(response){
                     console.log(response); 
                      $("#h5data").append(sessionStorage.getItem("word"));
                      $("#WC").append(response.doc.count);

                      $.each(response.doc.occurrence, function (key, value) {  
          $('#exampleid').append("<tr>\
                <td>"+key+"</td>\
                <td>"+value+"</td>\
                </tr>");


        });

This is my ajax response which is showing the occurrence but now I have to highlight the word which user has searched.

GhaLzai
  • 3
  • 2
  • In other words, you have a string of text and you want to highlight a word or words (possibly using a ). I'll bet there are existing solutions for that; did you look for these? When looking for existing answers, you need to ditch all irrelevant stuff (i.e. ajax, loop) –  May 14 '22 at 14:56
  • A quick way is to do `text.split(searchTerm).join('' + searchTerm + '')` and use CSS to highlight the text inside the spans. –  May 14 '22 at 14:58
  • No its user has types a word and then my api returns an array of occurrences of those words. – GhaLzai May 14 '22 at 15:01
  • So I want to highlight word inside that array which I receive in response. – GhaLzai May 14 '22 at 15:01
  • What are these occurrences? Sentences? –  May 14 '22 at 15:02
  • yes array of sentences it returns sentences which have that word in it – GhaLzai May 14 '22 at 15:03
  • Exactly. So ignore the array for a second, and think of the first sentence. Now look at my first comment again. I told you that the fact that you have multiple sentences or the fact that you've loaded them via ajax does not matter at all. –  May 14 '22 at 15:04
  • Here's example code: https://jsfiddle.net/pc4jx593/ –  May 14 '22 at 15:07
  • Before posting here, you need to look for existing solutions. And you will only find them if you narrow down the actual problem you have, and remove all the irrelevant stuff. If you google "js highlight word in sentence" you will get [this](https://stackoverflow.com/questions/49893360/highlight-all-word-matches-of-sentence-of-text-javascript) as first result –  May 14 '22 at 15:10

0 Answers0