About this snippet

Help users spot their search terms instantly. This script scans the content and wraps matching keywords in a highlight tag, which makes long articles or lists much easier to scan.

Size
1.5 KB
Uses
HTML, CSS, JavaScript
Loads
Nothing external
Views
303

Collections

<div class="search-highlight">
  <input type="text" id="searchBox" placeholder="Search text...">
  <p id="contentText">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
  </p>
</div>
.search-highlight {
  font-family: system-ui, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
  max-width: 500px;
  margin: 0 auto;
}
#searchBox {
  width: 100%;
  padding: 10px;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  margin-bottom: 20px;
  font-size: 1rem;
  box-sizing: border-box;
}
#contentText {
  line-height: 1.6;
  color: #374151;
}
.highlight {
  background-color: #fef08a;
  color: #854d0e;
  font-weight: bold;
  border-radius: 2px;
  padding: 0 2px;
}
const searchBox = document.getElementById("searchBox");
const p = document.getElementById("contentText");
const originalText = p.innerText;

searchBox.addEventListener("input", function() {
  const val = this.value;
  if (val.trim() === "") {
    p.innerHTML = originalText;
    return;
  }
  
  // Create regular expression with global and case-insensitive flags
  const regex = new RegExp(`(${val})`, "gi");
  
  // Replace match with wrapped mark tag
  const newText = originalText.replace(regex, `<mark class="highlight">$1</mark>`);
  p.innerHTML = newText;
});
Esc
↑↓ moveEnter select

Start from a template

Open an .html file, or HTML, CSS, JS, Markdown, Less or TypeScript files. You can also drop them here. Styles and scripts go into their panes.

Share

Source

Keyboard shortcuts

Save