在大量文本中搜索特定内容是 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;
在上面的代码中,我们使用带有正则表达式的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>
在此示例中,我们有一个 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>
在此示例中,我们定义了一个名为“highlight”的 CSS 类,它为突出显示的文本应用所需的样式。在highlightText()函数中,我们检索搜索字符串,修剪它,并使用其文本内容检索contentElement的内容。然后,我们使用搜索字符串和标志“gi”(全局且不区分大小写)创建正则表达式。
接下来,我们对内容字符串使用 Replace() 方法,将所有出现的搜索字符串替换为突出显示的版本。我们不使用字符串替换,而是使用回调函数,将匹配的字符串包装在具有“highlight”类的 元素中。
最后,我们将 contentElement 的内部 HTML 设置为突出显示的内容。如果搜索字符串为空,我们通过将内部 HTML 设置为文本内容来恢复原始内容。
方法三:使用正则表达式
在此方法中,我们将利用正则表达式的强大功能来动态突出显示搜索到的字符串。正则表达式提供了一种灵活而强大的方法来匹配字符串中的模式。以下是我们如何使用正则表达式突出显示搜索到的字符串−
示例
<!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>
在此示例中,我们使用 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 Compatibility−This 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 Compatibility−Modern 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.
Flexibility−Regular 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!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

WebStorm Mac version
Useful JavaScript development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.