【问题标题】:Find and highlight word in text using JS使用 JS 查找并突出显示文本中的单词
【发布时间】:2019-03-15 13:53:17
【问题描述】:

我是 Javascript 新手。我有一个问题:如何突出显示输入中输入的文本中的单词。我只能完成检查这个词是否在文本中的部分,但无法在文本中突出显示这个词。提前谢谢大家!

   var paragraph = document.getElementById('paragraph').innerText; //PARAGRAPH
        input = document.getElementById('typed-text').value; //TYPED TEXT
        textIncludes = paragraph.includes(input); // TEXT INCLUDES WORD
    
    
    if (textIncludes === true) {
        alert('Word has been found')
    } else {
        alert('No matches found')
    }
 <div id="highlights">
            <div class="container">
                <div class="row">
                    <div class="col-md-12" id="paragraph">
                        <p>
                            Robotics is an interdisciplinary branch of engineering and science that includes mechanical engineering, electronics engineering, information engineering, computer science, and others. Robotics deals with the design, construction, operation, and use of robots, as well as computer systems for their control, sensory feedback, and information processing.
                            These technologies are used to develop machines that can substitute for humans and replicate human actions. Robots can be used in many situations and for lots of purposes, but today many are used in dangerous environments (including bomb detection and deactivation), manufacturing processes, or where humans cannot survive (e.g. in space). Robots can take on any form but some are made to resemble humans in appearance. This is said to help in the acceptance of a robot in certain replicative behaviors usually performed by people. Such robots attempt to replicate walking, lifting, speech, cognition, and basically anything a human can do. Many of today's robots are inspired by nature, contributing to the field of bio-inspired robotics.
                            The concept of creating machines that can operate autonomously dates back to classical times, but research into the functionality and potential uses of robots did not grow substantially until the 20th century.[1] Throughout history, it has been frequently assumed that robots will one day be able to mimic human behavior and manage tasks in a human-like fashion. Today, robotics is a rapidly growing field, as technological advances continue; researching, designing, and building new robots serve various practical purposes, whether domestically, commercially, or militarily. Many robots are built to do jobs that are hazardous to people such as defusing bombs, finding survivors in unstable ruins, and exploring mines and shipwrecks. Robotics is also used in STEM (science, technology, engineering, and mathematics) as a teaching aid.
                            Robotics is a branch of engineering that involves the conception, design, manufacture, and operation of robots. This field overlaps with electronics, computer science, artificial intelligence, mechatronics, nanotechnology and bioengineering.
                        </p>
                    </div>
                    <div class="col-md-12 input-group mt-3">
                        <div class="input-group-prepend">
                            <span class="input-group-text" id="basic-addon1">
                                <i class="fas fa-pencil-alt"></i>
                            </span>
                        </div>
                        <input id="typed-text" type="text" class="form-control" placeholder="Type text">
                    </div>
                </div>
            </div>
        </div>

【问题讨论】:

    标签: javascript html input include highlight


    【解决方案1】:

    这是我的解决方案。我发现有两种方法可以实现这一点。在 Firefox 中,您可以使用 selection api。不幸的是,它在 Chrome 中不起作用。一个更简单的解决方案是匹配搜索文本并通过将其括在&lt;mark&gt; 标记中来突出显示它。

    var opar = document.getElementById('paragraph').innerHTML;
    
    function highlight() {
      var paragraph = document.getElementById('paragraph');
      var search = document.getElementById('typed-text').value;
      search = search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); //https://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
    
      var re = new RegExp(search, 'g');
      var m;
    
      if (search.length > 0)
        paragraph.innerHTML = opar.replace(re, `<mark>$&</mark>`);
      else paragraph.innerHTML = opar;
    }
    <div id="highlights">
      <div class="container">
        <div class="row">
          <div class="col-md-12" id="paragraph">
            <p>
              Robotics is an interdisciplinary branch of engineering and science that includes mechanical engineering, electronics engineering, information engineering, computer science, and others. Robotics deals with the design, construction, operation, and use of
              robots, as well as computer systems for their control, sensory feedback, and information processing. These technologies are used to develop machines that can substitute for humans and replicate human actions. Robots can be used in many situations
              and for lots of purposes, but today many are used in dangerous environments (including bomb detection and deactivation), manufacturing processes, or where humans cannot survive (e.g. in space). Robots can take on any form but some are made to
              resemble humans in appearance. This is said to help in the acceptance of a robot in certain replicative behaviors usually performed by people. Such robots attempt to replicate walking, lifting, speech, cognition, and basically anything a human
              can do. Many of today's robots are inspired by nature, contributing to the field of bio-inspired robotics. The concept of creating machines that can operate autonomously dates back to classical times, but research into the functionality and
              potential uses of robots did not grow substantially until the 20th century.[1] Throughout history, it has been frequently assumed that robots will one day be able to mimic human behavior and manage tasks in a human-like fashion. Today, robotics
              is a rapidly growing field, as technological advances continue; researching, designing, and building new robots serve various practical purposes, whether domestically, commercially, or militarily. Many robots are built to do jobs that are hazardous
              to people such as defusing bombs, finding survivors in unstable ruins, and exploring mines and shipwrecks. Robotics is also used in STEM (science, technology, engineering, and mathematics) as a teaching aid. Robotics is a branch of engineering
              that involves the conception, design, manufacture, and operation of robots. This field overlaps with electronics, computer science, artificial intelligence, mechatronics, nanotechnology and bioengineering.
            </p>
          </div>
          <div class="col-md-12 input-group mt-3">
            <div class="input-group-prepend">
              <span class="input-group-text" id="basic-addon1">
                                <i class="fas fa-pencil-alt"></i>
                            </span>
            </div>
            <input id="typed-text" type="text" class="form-control" placeholder="Type text" onkeyup="highlight()">
          </div>
        </div>
      </div>
    </div>

    这个想法很简单。在keyup 事件上(当用户完成按键时),highlight 函数将搜索文本中的所有出现,然后使用&lt;mark&gt; 标签突出显示它们。

    【讨论】:

    • 非常感谢您的回答。你的回答真的很好。但是我现在理解起来太复杂了(我的JS知识还不是很好)
    • @VaqifAghayev,简化了答案。请检查一下。
    • 太棒了。谢谢!我现在明白了
    • @VaqifAghayev,删除了编辑前剩下的几行!现在应该更清楚代码中发生了什么。随意提出任何问题,我将详细说明可能看起来令人困惑的部分
    • @jrook 谢谢你的回答。我有更复杂的问题。我可以在输入字段中键入一个短语并在文本中突出显示输入中的每个单词吗?
    【解决方案2】:

    使用这个例子:

    var input = document.getElementById('typed-text');
    
    input.onkeydown = function (e) {
    
        if (e.keyCode === 13) {
    
            var paragraph = document.getElementById('paragraph');
            var result = document.querySelector('.result-output');
            var regexp = new RegExp(this.value, 'g');
            var textIncludes = paragraph.textContent.match(regexp);
                
            if (result)
                result.remove();
    
            paragraph.innerHTML = paragraph.textContent.replace(
                regexp,
                '<span style="color:red">' + this.value + '</span>');
    
            paragraph.insertAdjacentHTML(
                'afterend',
                '<span class="result-output" style="display: block; padding: 5px; margin-top: 10px; background: #eee; color: green;">' + (textIncludes ? textIncludes.length : 0) + ' words has been found.</span>');
                
        }
    
    }
    <div id="highlights">
            <div class="container">
                <div class="row">
                    <div class="col-md-12" id="paragraph">
                        <p>
                            Robotics is an interdisciplinary branch of engineering and science that includes mechanical engineering, electronics engineering, information engineering, computer science, and others. Robotics deals with the design, construction, operation, and use of robots, as well as computer systems for their control, sensory feedback, and information processing.
                            These technologies are used to develop machines that can substitute for humans and replicate human actions. Robots can be used in many situations and for lots of purposes, but today many are used in dangerous environments (including bomb detection and deactivation), manufacturing processes, or where humans cannot survive (e.g. in space). Robots can take on any form but some are made to resemble humans in appearance. This is said to help in the acceptance of a robot in certain replicative behaviors usually performed by people. Such robots attempt to replicate walking, lifting, speech, cognition, and basically anything a human can do. Many of today's robots are inspired by nature, contributing to the field of bio-inspired robotics.
                            The concept of creating machines that can operate autonomously dates back to classical times, but research into the functionality and potential uses of robots did not grow substantially until the 20th century.[1] Throughout history, it has been frequently assumed that robots will one day be able to mimic human behavior and manage tasks in a human-like fashion. Today, robotics is a rapidly growing field, as technological advances continue; researching, designing, and building new robots serve various practical purposes, whether domestically, commercially, or militarily. Many robots are built to do jobs that are hazardous to people such as defusing bombs, finding survivors in unstable ruins, and exploring mines and shipwrecks. Robotics is also used in STEM (science, technology, engineering, and mathematics) as a teaching aid.
                            Robotics is a branch of engineering that involves the conception, design, manufacture, and operation of robots. This field overlaps with electronics, computer science, artificial intelligence, mechatronics, nanotechnology and bioengineering.
                        </p>
                    </div>
                    <div class="col-md-12 input-group mt-3">
                        <div class="input-group-prepend">
                            <span class="input-group-text" id="basic-addon1">
                                <i class="fas fa-pencil-alt"></i>
                            </span>
                        </div>
                        <input id="typed-text" type="text" class="form-control" placeholder="Type text">
                    </div>
                </div>
            </div>
        </div>

    【讨论】:

    • 如果您只按 Enter 键而不输入任何字符,它将匹配所有内容并显示 2328 words has been found。您需要在函数中添加输入长度检查。此外,html5 具有&lt;mark&gt; 标签,这可能是突出显示选定文本的更好选择。最后,我的回答会在用户输入查询时突出显示。
    • 最后,搜索括号会导致这段代码出现语法错误。您需要在开始搜索之前转义特殊字符。请参阅我的回答或here 了解如何执行此操作。
    【解决方案3】:

    使用replaceinput 替换为突出显示的input。例如通过&lt;b&gt;加粗html标签(或其他html标签):

    document.getElementById('paragraph').innerHTML = document.getElementById('paragraph').innerHTML.replace(input, "<b>"+input+"</b>");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多