In modern web development, it is often necessary to implement the function of highlighting keywords. For example, on a search result page, a user might enter a keyword and want to see the keyword highlighted in the relevant content. Below we will discuss how to implement this function through JavaScript, specificallyhighlightText
Methods are examples.
1. Understand the escapeRegExp method
escapeRegExp
Is a function that escapes special characters into regular expression safe characters. There are many special characters in regular expressions, such as.
、*
、+
etc. These characters have specific meanings in the regular. If we want these characters to match as normal characters, we need to escape them.
escapeRegExp(str) { return (/([.*+?^=!:${}()|[]/\])/g, '\$1'); }
This method uses a regular expression to input special characters in the string (e.g.*
、+
、?
etc.) Replace them with their escape characters (e.g.*
、+
、?
). This ensures that we can safely use any string entered by the user in a regular expression, regardless of whether it contains special characters or not.
2. The core method of highlighting text
highlightText
The core function of the method is to find and highlight matches in text based on the keywords entered by the user. It uses the aforementionedescapeRegExp
Methods to ensure that each keyword is correctly escaped and then use regular expressions to implement highlighting.
highlightText(fieldValue) { const keyword = || ''; if (!keyword) return fieldValue; const keywords = (''); if ( === 0 || !fieldValue) return fieldValue; const regexString = (keyword => `(${(keyword)})`).join('|'); const regex = new RegExp(regexString, 'gi'); return (regex, (match) => { return `<span class="highlight">${match}</span>`; }); }
Code parsing:
Get keywords:First fromqueryParams
Get the keywords entered by the user (). If no keyword is entered, the original text will be returned directly.
Split keywords: Split the entered keywords into an array by characters. If the split array is empty orfieldValue
It is empty itself and returns directly to the original text.
Generate regular expressions:usemap
The method escapes each character and splices all escaped characters into a large regular expression string. Used here|
To separate each character, represent the "or" operation, that is, if any keyword character appears in the text, it will be matched.
Regular replacement:passreplace
Method, usespan
The tag wraps all matching characters for highlighting.'gi'
Flags indicate global matches and are case-insensitive.
Return to the highlighted text: Return the highlighted text as HTML and can be inserted directly into the page.
3. How to use highlightText
Suppose we have a component that displays a piece of text and wants to highlight the keywords entered by the user in the text. Can be called like thishighlightText
method:
<template> <div v-html="highlightText('This is a test text, the test keywords are highlighted')"></div> </template> <script> export default { data() { return { queryParams: { keyword: 'test' } }; }, methods: { escapeRegExp(str) { return (/([.*+?^=!:${}()|[]/\])/g, '\$1'); }, highlightText(fieldValue) { const keyword = || ''; if (!keyword) return fieldValue; const keywords = (''); if ( === 0 || !fieldValue) return fieldValue; const regexString = (keyword => `(${(keyword)})`).join('|'); const regex = new RegExp(regexString, 'gi'); return (regex, (match) => { return `<span class="highlight">${match}</span>`; }); } } }; </script> <style scoped> .highlight { background-color: yellow; } </style>
In this example, wev-html
The directive renders the highlighted text to the page and sets the highlighted background color through CSS. Keywords entered by userstest
Will be highlighted in the text.
4. Summary
Through the above method, we can easily implement a function of highlighting keywords, whether it is used for search results display or other scenes that require text highlighting. This method not only supports simple character highlighting, but also correctly handles special characters entered by users, ensuring the robustness and security of functions.
This is the end of this article about Vue implementing multiple keyword highlighting functions. For more related Vue keyword highlighting content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!