You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改JavaScript代码实现文本中混合多词的搜索与高亮?

问题

我需要一款通过表单和搜索按钮实现的文本单词搜索JavaScript代码。目前找到的代码仅支持连续多词搜索,无法处理混合排列的多词,请问需要进行哪些修改?

现有代码
<!DOCTYPE html>
<html lang="en">
 <title>Word finder</title>
  <head>
    <meta charset="UTF-8" />
    <title>Text Finder</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link rel="stylesheet" href="style.css" />
    <link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@500&display=swap" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
* {
  padding: 0;
  margin: 0;
  outline: 0;
  font-family: 'IBM Plex Sans', sans-serif;
}
body {
    height: 100vh;
    width: 100vw; 
    overflow: hidden;
}
.content {
  width: 80%;
  margin: 50px auto;
}
h1 {
  text-align: center;
}
.form {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: auto;
  width: 100%;
  max-width: 320px;
  height: 50vh;
}
input#keyword {
  font-size: 18px;
  padding: 10px 20px;
  outline: 0;
  border: 1px solid #0f62fe;
  width: auto;
}
span.highlight {
  color: black; background-color:yellow;
  text-shadow: 0 1px 1px red;
}
</style>

  </head>
  <body>
    <div class="content">
      <p>English texts for beginners to practice reading and comprehension online and for free. Practicing your comprehension 
of written English will both improve your vocabulary and understanding of grammar and word order. The texts below are designed 
to help you develop while giving you an instant evaluation of your progress.</p>
    </div>
    <h1>Find the word in paragraph</h1>

    <div class="form">
      <input type="text" id="keyword" class="form_control" placeholder="Search...">
    </div>

    <script>
      function textFind(keyword) {
        if(keyword) {
          var content = $("p").text();
          var searchText = new RegExp(keyword, "ig");
          var matches = content.match(searchText);       

          if(matches) {
            $("p").html(content.replace(searchText, function(match){
              return "<span class='highlight'>"+match+"</span>";
            }));
          }else {
            $('.highlight').removeClass('highlight');
          }
        }else{
          $('.highlight').removeClass('highlight');
        }
      }
      $(document).ready(function(){
        $('#keyword').on('keyup', function(){
          textFind($(this).val());
        })
      });
    </script>
  </body>
</html>
修改方案
  • 拆分搜索关键词:将输入文本按空格分割为独立单词,过滤空字符串(处理连续空格的情况)。
  • 构建多关键词正则:用|连接所有拆分后的关键词,生成可匹配任意单个关键词的正则表达式,保留大小写不敏感(i)和全局匹配(g)标志。
  • 修复高亮嵌套问题:每次搜索前先还原段落原始文本,避免多次搜索导致<span>标签嵌套。
  • 添加搜索按钮:完善表单结构,增加搜索按钮,支持点击触发搜索,同时保留原有的键盘输入实时搜索功能。
修改后的完整代码
<!DOCTYPE html>
<html lang="zh-CN">
 <title>单词查找器</title>
  <head>
    <meta charset="UTF-8" />
    <title>文本查找器</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@500&display=swap" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
* {
  padding: 0;
  margin: 0;
  outline: 0;
  font-family: 'IBM Plex Sans', sans-serif;
}
body {
    height: 100vh;
    width: 100vw; 
    overflow: hidden;
}
.content {
  width: 80%;
  margin: 50px auto;
}
h1 {
  text-align: center;
}
.form {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  margin: auto;
  width: 100%;
  max-width: 400px;
  height: 50vh;
}
input#keyword {
  font-size: 18px;
  padding: 10px 20px;
  outline: 0;
  border: 1px solid #0f62fe;
  flex: 1;
}
button#searchBtn {
  font-size: 18px;
  padding: 10px 20px;
  border: none;
  background-color: #0f62fe;
  color: white;
  cursor: pointer;
}
span.highlight {
  color: black; 
  background-color: yellow;
  text-shadow: 0 1px 1px red;
}
</style>

  </head>
  <body>
    <div class="content">
      <p id="originalText">English texts for beginners to practice reading and comprehension online and for free. Practicing your comprehension 
of written English will both improve your vocabulary and understanding of grammar and word order. The texts below are designed 
to help you develop while giving you an instant evaluation of your progress.</p>
    </div>
    <h1>在段落中查找单词</h1>

    <div class="form">
      <input type="text" id="keyword" class="form_control" placeholder="输入单词搜索...">
      <button id="searchBtn">搜索</button>
    </div>

    <script>
      // 保存原始文本,用于每次搜索前还原
      const originalContent = $('#originalText').text();

      function textFind(keyword) {
        // 先还原原始文本
        $('#originalText').text(originalContent);
        
        if(keyword.trim()) {
          // 拆分关键词,过滤空字符串
          const keywords = keyword.trim().split(/\s+/).filter(word => word);
          // 构建正则:匹配任意一个关键词,大小写不敏感、全局匹配
          const searchPattern = keywords.map(word => $.escapeRegExp(word)).join('|');
          const searchText = new RegExp(searchPattern, 'ig');
          
          const content = $('#originalText').text();
          const matches = content.match(searchText);       

          if(matches) {
            $('#originalText').html(content.replace(searchText, function(match){
              return "<span class='highlight'>"+match+"</span>";
            }));
          }
        }
      }

      $(document).ready(function(){
        // 键盘输入实时搜索
        $('#keyword').on('keyup', function(){
          textFind($(this).val());
        });
        // 点击搜索按钮触发搜索
        $('#searchBtn').on('click', function(){
          textFind($('#keyword').val());
        });
      });
    </script>
  </body>
</html>

内容的提问来源于stack exchange,提问作者Andrecoder24

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 08:25:26