← All examples

JavaScript Productivity substack.com

Substack: quick in-post search

Ctrl+Shift+F opens a search prompt that highlights every match of the phrase in the post body.

Code to copy

// Quick in-post search: press Ctrl+Shift+F to highlight matches in the article
(function () {
  function findRoot() {
    return document.querySelector('.body.markup, .available-content, [class*="postBody"]') || document.body;
  }
  function clearMarks(root) {
    root.querySelectorAll('mark[data-jz-search]').forEach(function (m) {
      var p = m.parentNode; p.replaceChild(document.createTextNode(m.textContent), m); p.normalize();
    });
  }
  function mark(root, q) {
    if (!q) { return 0; }
    var rx = new RegExp(q.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi');
    var walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, null);
    var nodes = [], n; while ((n = walker.nextNode())) { if (rx.test(n.nodeValue)) { nodes.push(n); } }
    var count = 0;
    nodes.forEach(function (node) {
      var span = document.createElement('span');
      span.innerHTML = node.nodeValue.replace(rx, function (m) { count++; return '<mark data-jz-search style="background:#fde68a;color:#111;">' + m + '</mark>'; });
      node.parentNode.replaceChild(span, node);
    });
    return count;
  }
  document.addEventListener('keydown', function (e) {
    if (!(e.ctrlKey && e.shiftKey && (e.key === 'F' || e.key === 'f'))) { return; }
    e.preventDefault();
    var root = findRoot(); clearMarks(root);
    var q = prompt('Search inside post:'); if (q == null || q === '') { return; }
    var n = mark(root, q);
    alert(n + ' match(es) for "' + q + '"');
    var first = root.querySelector('mark[data-jz-search]');
    if (first) { first.scrollIntoView({ behavior: 'smooth', block: 'center' }); }
  });
})();

How to use this example

  1. Copy the code with the button above.
  2. Install JustZix (2 minutes) and open the extension on the target page.
  3. Add a new rule matching that page.
  4. Paste the code into the rule's JavaScript panel and save — it runs on every page visit.

Rate this example

No ratings yet — be the first.

Does this example work?

Snippets are useless without somewhere to paste them.

JustZix takes 2 minutes to install and runs your code on every matching page. No account, no payment.

Download free See use cases