JS问题:在大文本中搜索一串小文本,打印成div并将大文本中的小文本涂成红色

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

基本上我需要创建一大一小两个文本框。然后在 div 内打印大文本框的文本,但无论我在小文本框中写的字符串出现在哪里,我都需要使用我们将定义红色 [=17= 的跨度将其着色为红色] 和 indexof()

这就是我目前的情况:

 <!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>

您可以执行以下操作

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;
}