Search code examples
javascripthtmlindexof

JS question : Search for a string of a small area text inside a large one, print it in a div and color the small string inside the large one in red


Basically I need to create two text boxes one large and one small. Then print inside the div the text of the large text box but wherever the string I wrote in the small text box appears i need to color it with red color by using a span where we will define a red class and by indexof() only

thats what i have so far :

 <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>project2</title>
        <style>
            span{
           color:red;
            }
        </style>
    </head>
    <body dir="ltr">
        <label>
            string 1 
            <input id='string1' type="text" size=10 required>
        </label>
        <br>
        <br>
        <br>
        <label>
            string 2
        <textarea id="string2" name="string2" rows="4" cols="50"></textarea></label>
        <br>
        <br>
        <button id="search for" onclick="search();" type=button>search for</button>
        <div id='rslt' style='text-align: center;font-size: 1em; font-weight: bolder;' value=""></div>
        <script>
        function search() 
        {
               
            let tstring1=(document.getElementById("string1").value.toString().trim());
            let tstring2=(document.getElementById("string2").value.toString().trim());
            
            if(tstring1==""|| tstring1==" "|| tstring2==""||tstring2==" ")
            {
                document.getElementById("rslt").innerHTML="you have to enter a string";
                return;
            }
            while(tstring2.indexOf(tstring1) != -1) {
                tstring2 = tstring2.replace(tstring1, '[X]');
                }
             while(tstring2.indexOf('[X]') != -1) {
                tstring2 = tstring2.replace('[X]', '<span ??>' + tstring1 + '</span>');
          }
           $("rslt").html(tstring2);
            
        }
    </script>
    </body>
    </html>

Solution

  • Here is what you can do

    function search() 
    {
        let tstring1=(document.getElementById("string1").value.toString().trim());
        let tstring2=(document.getElementById("string2").value.toString().trim());
        i = -1;
        index = [];
        while ((i = tstring2.indexOf(tstring1, i+1)) != -1){
            index.push(i);
        }
        for(let i = 0 ; i < index.length; i++) {
            tstring2 = tstring2.replace(tstring2.substr(index[i],tstring1.length),"<span>" + tstring1 + "<\span>");
        }
        $("#rslt").innerHtml = tstring2;
    }