
Search-Text-Highlighter.js is a tiny JavaScript library that allows you to search for specific text within a paragraph and highlights all instances of it.
It is perfect for situations where you have a lot of text and need to locate specific keywords or phrases. Let’s say you have a long article or report, and you need to find all mentions of a particular topic. Instead of manually scanning the entire document, you can simply enter the keyword into the search field, and the library will instantly highlight all occurrences.
How it works:
- The user enters the text they want to search for in the designated input field.
- When the user clicks the ‘Search’ button, the library retrieves the search query and the target paragraph element.
- The library then escapes any special characters in the search query to ensure accurate pattern matching.
- A regular expression pattern is created using the search query, and the library searches the paragraph text for all matches.
- If matches are found, the library highlights the matching text by wrapping it in an HTML `<mark>` element, which applies a custom background color.
- The number of matches found is then displayed above the paragraph, and success message is shown.
- If no matches are found, the paragraph content remains unchanged, and a red ‘No results found’ message is displayed.”
How to use it:
1. Download and load the main script ‘Search-Text-Highlighter.js’ in the html.
<script src="Search-Text-Highlighter.js"></script>
2. Add the unique ID ‘paragraph’ to your content block.
<p id="paragraph"> ... </p>
3. Create a search field next to the paragraph.
<input type="text" id="text-to-search" placeholder="Search..."> <button onclick="search()">Search</button> <div id="result"></div>
4. Apply your own styles to the highlighted text.
mark {
background-color: yellow;
font-weight: bold;
}






