Search code examples
javascriptphphighlight

Highlight exact text inside paragraphs generated by foreach loop


I'm using PHP to import some data from API as JSON then decode it as array then using foreach() loop to print it out

Example

// comes for api or database or whatever in json format
$decoded = json_decode($content, true);
foreach($decoded as $paragrah){
echo $paragrah . '<br />;
}

Demo Results

hello world from reddish hair Mars
hello world from my beautiful gas of Saturn
hello world from cold one Neptune
hello world from my big one Jupiter

Now using JAVASCRIPT or with jQuery How to highlight exact text "from my" in each paragraph if found to be like this image

enter image description here

My Try (Failed)

<style>
.highlight {
    background-color: #fff34d;
    -moz-border-radius: 5px;
    -webkit-border-radius: 5px;
    border-radius: 5px;
    -moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7);
    -webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7);
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7);
}
</style>

    <script type="text/javascript">
    function highlight(text) {
      var inputText = document.getElementById("inputText");
      var innerHTML = inputText.innerHTML;
      var index = innerHTML.indexOf(text);
      if (index >= 0) {
       innerHTML = innerHTML.substring(0,index) + "<span class='highlight'>" + innerHTML.substring(index,index+text.length) + "</span>" + innerHTML.substring(index + text.length);
       inputText.innerHTML = innerHTML;
      }
    }
    </script>

    <div id="inputText">
        <?php
        // comes for api or database or whatever in json format
        $decoded = json_decode($content, true);
        foreach($decoded as $paragrah){
        echo $paragrah . '<br />;
        }
        ?>
    </div>
    <script type="text/javascript">highlight('from my');</script>

The Problem

it only highlight text "from my" only in one paragraph once found as seen in this image!

enter image description here


Solution

  • Here is how you can do it an update of your own

    function highlight(text) {
      var inputText = document.getElementById("inputText");
      var innerHTML = inputText.innerHTML;
      var index = innerHTML.indexOf(text);
      if (index >= 0) {
        innerHTML = innerHTML.replace(/from my/gi, '<span class="highlight">from my</span>');
       inputText.innerHTML = innerHTML;
      }
    }
    highlight('from my');
    

    Just need to update a single line of code https://prnt.sc/qeo45n