Search for words on the website

Asked

Viewed 119 times

3

I’ve been practicing web programming for a while. At the moment I want to know how to do a Chrome Ctrl+F-style word search: by typing the characters it already points out the respective words. I understand that I will have to use Javascript.

Seria algo assim:

The search would only be for a page I’m implementing.

  • Welcome to Stackoverflow Ian. Please post an excerpt of the code you already have to get a better idea of the problem, I suggest you read this help article from the site: How to create a Minimum, Complete and Verifiable example.

  • But have you done something, tried or reached a certain point and failed? If yes, put the code here, editing your question for us to see. Would this search be on a specific site or on the web in general? Several details are missing from your question. Try to clarify more.

  • I edited the question. as you see in the image is just that. I believe it is something simple.

  • In addition to the tour already indicated in a comment above, a tip: if any answer solves your problem mark it as accepted. See how in https://i.stack.Imgur.com/jx7Ts.png and why in https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079

2 answers

6


Using the libraries jquery.min.js and jquery.mark.min.js

This code marks all typed words found.

$(function() {
  $("input").on("input.highlight", function() {
    // Determina o termo de pesquisa
    var buscaPalavra = $(this).val();
    // Destacar o termo de pesquisa dentro de um contexto específico, no caso body
    $("body").unmark().mark(buscaPalavra);
  }).trigger("input.highlight").focus();
});
mark {
  background: orange;
  color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/mark.js/7.0.0/jquery.mark.min.js"></script>
<input type="text" value="palavras caracteres">

<h4>Buscar palavras na página web</h4>
<span style="color: rgb(80, 80, 80);">
Venho praticando programação web há um tempo. No momento quero saber como faço um buscador de palavras estilo Ctrl+F do Chrome: ao digitar os caracteres ele já me aponta as palavras respectivas. Entendo que terei que usar o JavaScript.</span>

Similar to Google Chrome Search

    window.onload=function(){
      
$(function() {

  // the input field
  var $input = $("input[type='search']"),
    // clear button
    $clearBtn = $("button[data-search='clear']"),
    // prev button
    $prevBtn = $("button[data-search='prev']"),
    // next button
    $nextBtn = $("button[data-search='next']"),
    // the context where to search
    $content = $("body"),
    // Objeto jQuery para salvar elementos <mark>
    $results,
    // the class that will be appended to the current
    // focused element
    currentClass = "current",
    // top offset for the jump (the search bar)
    offsetTop = 50,
    // the current index of the focused element
    currentIndex = 0;

  /**
   * Jumps to the element matching the currentIndex
   */
  function jumpTo() {
    if ($results.length) {
      var position,
        $current = $results.eq(currentIndex);
      $results.removeClass(currentClass);
      if ($current.length) {
        $current.addClass(currentClass);
        position = $current.offset().top - offsetTop;
        window.scrollTo(0, position);
      }
    }
  }

  /**
   * Searches for the entered keyword in the
   * specified context on input
   */
  $input.on("input", function() {
  	var searchVal = this.value;
    $content.unmark({
      done: function() {
        $content.mark(searchVal, {
          separateWordSearch: true,
          done: function() {
            $results = $content.find("mark");
            currentIndex = 0;
            jumpTo();
          }
        });
      }
    });
  });

  /**
   * Clears the search
   */
  $clearBtn.on("click", function() {
    $content.unmark();
    $input.val("").focus();
  });

  /**
   * Next and previous search jump to
   */
  $nextBtn.add($prevBtn).on("click", function() {
    if ($results.length) {
      currentIndex += $(this).is($prevBtn) ? -1 : 1;
      if (currentIndex < 0) {
        currentIndex = $results.length - 1;
      }
      if (currentIndex > $results.length - 1) {
        currentIndex = 0;
      }
      jumpTo();
    }
  });
});


    }
    mark {
  background: yellow;
}

mark.current {
  background: orange;
}

.header {
  padding: 10px;
  width: 100%;
  background: #eee;
  position: fixed;
  top: 0;
  left: 0;
}

.texto {
  margin-top: 50px;
}
<script src="https://cdn.jsdelivr.net/g/[email protected],[email protected](jquery.mark.min.js)"></script>
<div class="header">
  Search:
  <input type="search" placeholder="Lorem">
  <button data-search="next">&darr;</button>
  <button data-search="prev">&uarr;</button>
  <button data-search="clear">✖</button>
</div>

<div class="texto">
  <h4>Buscar palavras na página web</h4>
<span style="color: rgb(80, 80, 80);">
<p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis eu ullamcorper orci, eget porttitor justo. Aliquam id sollicitudin elit. Nulla in sodales ipsum. Donec vulputate venenatis magna. Vestibulum sit amet leo lacinia, cursus lectus in, gravida
    metus. In ultricies sed tortor non pellentesque. Mauris quis tempor neque. Donec nec sagittis magna. Integer fringilla posuere metus eu mollis. Ut ac porta metus. Duis sed lacinia metus. Nunc malesuada iaculis risus vitae bibendum.
  </p>

  <p>
    Vivamus posuere condimentum leo eu hendrerit. Pellentesque placerat iaculis ante a rhoncus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum eu ipsum ac magna congue congue sed maximus tortor. Vivamus id odio elementum, vehicula nunc
    ut, efficitur felis. Nullam hendrerit velit libero, gravida porttitor tortor ullamcorper eu. Ut ut lectus non enim sagittis aliquam quis in orci. Donec a arcu eu eros cursus cursus. Donec dictum dignissim tellus, dictum egestas purus pellentesque
    sed.
  </p>

  <p>
    Vestibulum eu ornare urna, nec aliquam lectus. Phasellus eu odio sapien. Vestibulum eu turpis at lorem sagittis posuere. Quisque tellus nunc, facilisis id lacus nec, ornare rhoncus elit. Vivamus vehicula eros a condimentum venenatis. Sed orci massa, pulvinar
    sed erat nec, pellentesque suscipit leo. Mauris lobortis tincidunt nunc, sed tempus ex congue vitae. Curabitur lobortis mauris in ex malesuada, quis vehicula neque lobortis. Curabitur aliquam porttitor tellus eget tempus. Donec maximus tempus tristique.
    Aliquam tincidunt odio dictum, scelerisque ipsum ut, facilisis quam. Ut nec malesuada neque.
  </p>

  <p>
    Proin felis eros, tincidunt vitae scelerisque sit amet, dictum nec ante. Praesent tincidunt ac lacus nec elementum. Vivamus sed gravida purus, sed efficitur tortor. Nulla non molestie arcu. Sed tincidunt consectetur ligula sed lobortis. In non sapien
    ac urna lacinia placerat sed nec lacus. Aenean lobortis tincidunt sapien a hendrerit. Quisque eu turpis accumsan nisl blandit efficitur.
  </p>

  <p>
    Nam sit amet pellentesque est. Sed ligula turpis, ultricies sit amet mattis elementum, tristique non risus. Phasellus at congue ex. Proin nisi leo, vestibulum vitae accumsan in, imperdiet id dolor. Quisque at blandit nisl. Class aptent taciti sociosqu
    ad litora torquent per conubia nostra, per inceptos himenaeos. Nunc eget metus augue. Morbi faucibus venenatis sapien, fermentum porttitor felis pharetra a. Nam interdum nibh tortor, quis maximus turpis blandit eget. Praesent in feugiat neque, sed
    vulputate quam. Curabitur erat quam, efficitur et congue quis, iaculis euismod libero. Quisque odio sapien, efficitur non mauris ac, tincidunt condimentum turpis.
  </p>

  <p>
    Maecenas dapibus aliquam vehicula. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Praesent convallis viverra leo quis porta. Sed sit amet porttitor quam. Fusce nec risus non augue consectetur ultricies. Aliquam
    elit lorem, tincidunt ac dolor vel, vulputate consectetur ex. In hac habitasse platea dictumst. Sed eget nisl aliquam, cursus odio nec, commodo lorem. Nulla mollis tortor eu odio rutrum vulputate. Donec condimentum molestie mauris, nec sodales nisi
    volutpat aliquam. Nulla mollis libero sed nibh volutpat, ac mollis elit tincidunt. Vestibulum cursus velit vitae felis aliquam ultricies. Donec vehicula dictum feugiat. Vestibulum volutpat sollicitudin sagittis.
  </p>

  <p>
    Aliquam consequat, diam eu ullamcorper porta, diam eros rhoncus turpis, in rutrum sem diam a risus. Duis lacinia velit sed ante feugiat venenatis. Aenean orci leo, dictum non finibus nec, dignissim quis eros. Nullam sit amet orci ac purus blandit commodo
    sit amet eget neque. Sed pellentesque dictum tortor. Ut dui erat, tempus in odio in, aliquet convallis mi. Morbi efficitur justo ante, quis ultricies turpis suscipit ac. Sed sit amet nisl rutrum, laoreet mauris id, ullamcorper orci. In facilisis nisi
    eget fringilla imperdiet. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Morbi ut ultricies dui. Pellentesque elit urna, imperdiet sed congue eget, hendrerit sed urna.
  </p>

  <p>
    Proin vel hendrerit nulla. Vivamus vehicula nibh nec lorem blandit, quis aliquam ipsum suscipit. Nulla at vestibulum felis. Aenean ac nibh eget enim molestie pulvinar. Duis nulla justo, tristique id nulla nec, faucibus imperdiet arcu. In vel pretium dui,
    at lobortis sapien. Phasellus ullamcorper id enim eget dictum. Ut imperdiet rutrum est a rutrum. Curabitur eget dignissim tellus. Fusce tempus leo nisl, vitae auctor diam feugiat sit amet. Vestibulum accumsan justo eget odio imperdiet, consectetur
    efficitur ex dapibus.
  </p>

  <p>
    Sed pharetra odio a nibh pharetra rutrum. Suspendisse ut ullamcorper lectus. Donec ipsum mauris, congue et lobortis sit amet, ultricies ac tellus. Sed nisi risus, condimentum at varius quis, condimentum ac velit. In condimentum, magna sed ornare eleifend,
    dolor nulla mollis felis, quis feugiat elit turpis non ipsum. Etiam aliquam est imperdiet dolor rutrum, at varius leo sodales. Morbi quis iaculis metus.
  </p>

  <p>
    Maecenas auctor nec ligula ac luctus. Nam sit amet euismod mauris. Donec et diam sit amet eros efficitur tempor. Mauris non erat sit amet nunc interdum pulvinar. Sed luctus hendrerit justo eget pulvinar. Cras non arcu sed ligula faucibus pulvinar. Sed
    egestas risus nisl. Duis quis arcu tempus, cursus erat ac, gravida enim. Cras et condimentum ante. Nullam eleifend egestas velit, quis semper est imperdiet non. Donec quis purus varius, placerat mi et, dictum lorem. Sed quis finibus nisi, vitae molestie
    metus. Donec lobortis eros quis vestibulum vulputate.
  </p>.</span>
</div>

See more in https://markjs.io/

  • Pow the solution of the boy above solved more or less the problem. because the filter appeared in the form of button. but this solution really was the best. Very helpful. Very grateful Leo Caracciolo solved my problem. I will study more in depth javascript and Jquery plugins to help also those who are in need of problems like this.

0

One way to do this with vanilla would be to use regular expressions

I made an example in code pen: https://codepen.io/lwauke/pen/WaJVwv

One way to do the regular expression you need would be by using the characters b that represent limits, w to represent numeric alpha characters and * that would be none or n occurrences.

The example below returns only the first occurrence:

// procura uma palavra que tenha a letra e
var pattern = /\b\w*e\w*\b/
'teste regex'.match(pattern)
// output: ["teste", index: 0, input: "teste regex", groups: undefined]

Use capture(parentheses) and the global flag to catch all occurrences

var pattern = /(\b\w*e\w*\b)/g
'teste regex'.match(pattern)
// output: ["teste", "regex"]

Use the replace function with $1 that will reference your capture:

var pattern = /(\b\w*e\w*\b)/g
'teste regex'.replace(pattern, '<span class="word">$1<span>')
// output: "<span class="word">teste<span> <span class="word">regex<span>"

(reference for regular expression query).

  • 1

    Thank you very much Lucas Wauke. this can also solve problems similar to mine. Thank you all!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.