Home > Web Front-end > JS Tutorial > How to highlight searched string results using JavaScript?

How to highlight searched string results using JavaScript?

PHPz
Release: 2023-09-01 12:49:02
forward
823 people have browsed it

如何使用 JavaScript 突出显示搜索到的字符串结果?

在大量文本中搜索特定内容是 Web 应用程序中的一项常见任务。然而,仅显示搜索结果而没有任何视觉指示可能会使用户难以识别和关注相关信息。这就是需要突出显示搜索字符串的地方。通过动态突出显示文本的匹配部分,我们可以改善用户体验,让用户更容易找到所需的内容。

在这篇博文中,我们将探索使用 JavaScript 突出显示搜索字符串的不同方法。我们将介绍从操作 HTML 内容到利用正则表达式和 CSS 样式的各种技术。无论您是为网站构建搜索功能还是开发基于文本的应用程序,这些方法都将使您能够增强搜索结果的可见性并提供更直观的用户界面。

方法 1 - 操作内部 HTML

突出显示搜索字符串的一种直接方法是操作包含文本的元素的内部 HTML。此方法涉及查找文本中出现的搜索字符串,并用 HTML 标记将其包裹起来,或应用内联样式以直观地突出显示它们。

要实现此方法,请按照以下步骤操作 -

  • 检索执行搜索的目标元素的内容。

  • 使用replace()方法或正则表达式查找搜索字符串并将其替换为突出显示的版本。

  • 用 HTML 标签包裹匹配的字符串或应用内联样式来突出显示它。

  • 将修改后的内容设置回目标元素的内部 HTML。

让我们用一个例子来说明这一点。假设我们有一个类名为“content”的 HTML 元素,并且我们想要突出显示其中出现的搜索字符串。我们可以使用以下 JavaScript 代码 -

// Get the target element
const contentElement = document.querySelector('.content');

// Retrieve the content
const content = contentElement.innerHTML;

// Replace the search string with the highlighted version
const highlightedContent = content.replace(/search-string/gi, '$&');

// Set the modified content back to the element
contentElement.innerHTML = highlightedContent;
Copy after login

在上面的代码中,我们使用带有正则表达式的replace()方法来查找所有出现的搜索字符串并将其替换为突出显示的版本。替换字符串中的 $& 代表匹配的字符串本身。我们用 元素包装它,并应用“highlight”类来设置样式。

示例

示例如下 -

<!DOCTYPE html>
<html>
<head>
   <style>
      .highlight {
         background-color: yellow;
         font-weight: bold;
      }
   </style>
</head>
<body>
   <div class="content">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
      Aliquam cursus maximus eros, non consequat nulla vulputate id. 
      Sed porttitor quam a felis viverra lacinia. 
      Vestibulum vestibulum massa at orci ultrices, in maximus tellus aliquam.
   </div>
   <form>
      <input type="text" id="searchInput" placeholder="Search...">
      <button type="button" onclick="highlightText()">Search</button>
   </form>
   <script>
      function highlightText() {
         const searchInput = document.getElementById('searchInput');
         const searchValue = searchInput.value.trim();
         const contentElement = document.querySelector('.content');
   
         if (searchValue !== '') {
         const content = contentElement.innerHTML;
         const highlightedContent = content.replace(
            new RegExp(searchValue, 'gi'),
            '<span class="highlight">$&</span>'
         );
         contentElement.innerHTML = highlightedContent;
         } else {
            contentElement.innerHTML = contentElement.textContent;
         }
      }
   </script>
</body>
</html>
Copy after login

在此示例中,我们有一个 HTML 文档,其内容 div 包含一些示例文本。我们还有一个供用户输入搜索字符串的输入字段和一个搜索按钮。当用户点击搜索按钮时,就会触发highlightText()函数。

在highlightText()函数中,我们从输入字段中检索搜索字符串并修剪任何前导或尾随空格。如果搜索字符串不为空,我们将使用其内部 HTML 检索 contentElement 的内容。然后,我们使用 Replace() 方法和正则表达式将所有出现的搜索字符串(不区分大小写)替换为突出显示的版本。匹配的字符串 ($&) 包装在具有“highlight”类的 元素中。

如果搜索字符串为空,我们通过将内部 HTML 设置为 contentElement 的文本内容来恢复原始内容。

方法二:使用CSS类进行高亮

在此方法中,我们将利用 CSS 类来突出显示搜索到的字符串,而不是操作内部 HTML。实现方法如下。

示例

<!DOCTYPE html>
<html>
<head>
   <style>
      .highlight {
         background-color: yellow;
         font-weight: bold;
      }
   </style>
</head>
<body>
   <div class="content">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
      Aliquam cursus maximus eros, non consequat nulla vulputate id. 
      Sed porttitor quam a felis viverra lacinia. 
      Vestibulum vestibulum massa at orci ultrices, in maximus tellus aliquam.
   </div>

   <form>
      <input type="text" id="searchInput" placeholder="Search...">
      <button type="button" onclick="highlightText()">Search</button>
   </form>

   <script>
      function highlightText() {
         const searchInput = document.getElementById('searchInput');
         const searchValue = searchInput.value.trim();
         const contentElement = document.querySelector('.content');
   
         if (searchValue !== '') {
            const content = contentElement.textContent;
            const regex = new RegExp(searchValue, 'gi');
            const highlightedContent = content.replace(
               regex,
               (match) => `<span class="highlight">${match}</span>`
            );
            contentElement.innerHTML = highlightedContent;
          } else {
             contentElement.innerHTML = contentElement.textContent;
          }
       }
   </script>
</body>
</html>
Copy after login

在此示例中,我们定义了一个名为“highlight”的 CSS 类,它为突出显示的文本应用所需的样式。在highlightText()函数中,我们检索搜索字符串,修剪它,并使用其文本内容检索contentElement的内容。然后,我们使用搜索字符串和标志“gi”(全局且不区分大小写)创建正则表达式。

接下来,我们对内容字符串使用 Replace() 方法,将所有出现的搜索字符串替换为突出显示的版本。我们不使用字符串替换,而是使用回调函数,将匹配的字符串包装在具有“highlight”类的 元素中。

最后,我们将 contentElement 的内部 HTML 设置为突出显示的内容。如果搜索字符串为空,我们通过将内部 HTML 设置为文本内容来恢复原始内容。

方法三:使用正则表达式

在此方法中,我们将利用正则表达式的强大功能来动态突出显示搜索到的字符串。正则表达式提供了一种灵活而强大的方法来匹配字符串中的模式。以下是我们如何使用正则表达式突出显示搜索到的字符串

示例< /h3>
<!DOCTYPE html>
<html>
<head>
   <style>
      .highlight {
         background-color: yellow;
         font-weight: bold;
      }
   </style>
</head>
<body>
   <div id="content">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
      Aliquam cursus maximus eros, non consequat nulla vulputate id. 
      Sed porttitor quam a felis viverra lacinia. 
      Vestibulum vestibulum massa at orci ultrices, in maximus tellus aliquam.
   </div>   
   <form>
      <input type="text" id="searchInput" placeholder="Search...">
      <button type="button" onclick="highlightText()">Search</button>
   </form>   
   <script>
      function highlightText() {
         const searchInput = document.getElementById('searchInput');
         const searchValue = searchInput.value.trim();
         const contentElement = document.getElementById('content');
   
         if (searchValue !== '') {
         const content = contentElement.innerHTML;
         const regex = new RegExp(`(${searchValue})`, 'gi');
         const highlightedContent = content.replace(
            regex,
            '<span class="highlight">$1</span>'
         );
         contentElement.innerHTML = highlightedContent;
         } else {
            contentElement.innerHTML = contentElement.textContent;
         }
      }
   </script>
</body>
</html>
Copy after login

在此示例中,我们使用 RegExp 构造函数定义正则表达式,传递搜索值和标志“gi”(全局且不区分大小写)。我们将搜索值括在括号中以将其捕获为一个组。

Inside the highlightText() function, we retrieve the search string, trim it, and retrieve the contentElement's content using its inner HTML. We then use the Replace() method on the content string, providing a regular expression and a replacement string that wraps the matching search value in a element with the "highlight" class.

Method comparison

Now, let’s compare the methods we introduced -

Method 1: Manipulate internal HTML

  • Performance This method works well for small to medium-sized texts, but may be slower for larger texts due to string manipulation operations.

  • Easy to Implement Relatively easy to implement using JavaScript’s built-in string functions.

  • Flexibility It provides flexibility in customizing highlight styles and handling case sensitivity.

  • Browser CompatibilityThis method is widely supported in modern browsers.

Method 2: Use CSS classes for highlighting

  • Performance This method may be slower compared to other methods, especially when processing large text or frequent DOM manipulation overhead during search operations.

  • Easy to implement It requires a good understanding of DOM manipulation and may involve more complex code.

  • Flexibility It provides flexibility in customizing highlight styles and handling case sensitivity.

  • Browser CompatibilityModern browsers support this method, but different implementations may behave slightly differently.

Method 3: Use regular expressions

  • Performance Regular expressions can search and highlight text very efficiently, even with large amounts of data.

  • Easy to Implement Implementing regular expressions requires a deep understanding of their syntax, which may be more challenging for beginners.

  • FlexibilityRegular expressions provide powerful pattern matching capabilities, allowing advanced search and highlighting options .

  • Browser Compatibility Modern browsers widely support regular expressions, but some older versions may have limitations in regular expression support or Variety.

in conclusion

In this article, we explored different ways to highlight search strings using JavaScript. Each approach has its own advantages and considerations, so it's important to evaluate them based on factors such as performance, ease of implementation, flexibility, and browser compatibility.

By understanding these methods, you can enhance your web application's search capabilities and provide a more intuitive user experience.

The above is the detailed content of How to highlight searched string results using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template