Search for entered values in an input

Asked

Viewed 84 times

-2

I’m having trouble searching for the typed content in a input and I don’t know what’s wrong, this is the code:

let g1=document.querySelector("#g")
let p1=document.querySelector("#p")
let arr = ['top', 'topper', 'bot', 'bottom', 'botão', 'test'];
let regex = new RegExp('g1');
let newArr = [];
// mesma coisa que for (let i = 0; i < arr.length; i++)
for (let i in arr) {
  // Verifica se o item da array bate com a regex.
  if (arr[i].match(regex)) {
    // Se bater com a regex vai colocar no final da nova array;
    newArr.push(arr[i]);

  }
}
console.log('newArr: ', newArr);
for (let i in newArr) {
p1.innerText += newArr[i] + '   ';
}
<input id="g" type="text">
<button type="submit">pesquisar</button>
<div id="p"></div>

1 answer

3


In doing RegExp('g1'), you are creating a regex that searches for the exact text "g1", and not for the value of what was typed in input id="g".

Another detail is that you should only perform the search after the button is clicked. The way you did, the code runs as soon as the page loads, and then no longer runs.

So one way to do it is:

let arr = ['top', 'topper', 'bot', 'bottom', 'botão', 'test'];
// só executar a busca quando o botão for clicado
document.querySelector('#pesquisar').addEventListener('click', function() {
  let busca = document.querySelector("#g").value; // pegar o valor do input
  let regex = new RegExp(busca); // usar o valor do input na regex
  let newArr = [];
  for (let texto of arr) {
    if (texto.match(regex)) {
      newArr.push(texto);
    }
  }
  console.log('newArr: ', newArr);
  document.querySelector("#p").innerText = newArr.join(' ');
});
<input id="g" type="text">
<button id="pesquisar" type="submit">pesquisar</button>
<div id="p"></div>

Notice I used join to merge the results into a single string instead of the for. The difference is that if you do a search that finds something, the value of div is updated, but if the next search does not find anything, the content of div is not erased (for it will not enter the for). Already using join, if the array is empty, an empty string is returned and the content is "deleted" if no result is found.


Another way to search is to use filter instead of the for, which already returns an array with the elements satisfying the condition (or an empty array, if none is found):

let newArr = arr.filter(texto => texto.match(regex));

One detail is that if characters are typed that have special meaning in regex (such as ., parentheses, brackets, etc.), this may result in an invalid expression and will error when constructing the RegExp. In this case, you must use some escape function to put \ before these characters (here has some alternatives).

Another point of attention is that creating a regex with a string that the user typed requires some care (read here for more details).


It is also worth remembering that if you are only searching for the elements that have the passage typed, nor need regex. Just use includes, that checks if one string is substring from another:

let arr = ['top', 'topper', 'bot', 'bottom', 'botão', 'test'];
// só executar a busca quando o botão for clicado
document.querySelector('#pesquisar').addEventListener('click', function() {
  let busca = document.querySelector("#g").value; // pegar o valor do input
  let newArr = arr.filter(texto => texto.includes(busca));
  console.log('newArr: ', newArr);
  document.querySelector("#p").innerText = newArr.join(' ');
});
<input id="g" type="text">
<button id="pesquisar" type="submit">pesquisar</button>
<div id="p"></div>

  • it would be possible to take the values of the arrays achieved in the search and list them in another html page that would be opened after the click event happens?

  • @Yuricassu That’s the case with ask another question, detailing better what you want to do (don’t forget to search on the site before, as you may already have questions about it). Ask another question is better because you have more space to detail and put the code you already tried, besides being visible on the main page for all users (here in the comments has no space to explain everything and only I will see) :-)

  • I was already thinking about asking a question, but I think you can answer me around here. Is there any difference that should be taken into account when using the includes in place of regex (or vice versa) for the single match case? Something relevant to performance, for example?

  • 1

    @Cmtecardeal includes is to see if one string is substring from another (case sensitive), is that what you call "unique"? For anything more complicated you can use regex (depending on the case, it may or may not be the best option). I haven’t tested, but I’m pretty sure regex is slower in virtually every case, after all it has to be compiled and has an enormous complexity under the table. But choosing one or the other depends on what you want to do...

  • That was the case. From what you said, probably includes should be more performative, but I’m going to benchmark to confirm.

Browser other questions tagged

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