How to treat High and Low Letters Box along with Symbols

Asked

Viewed 749 times

4

I got the following snippet spinning pretty:

function busca() {
  var str = document.getElementById('txt').value;
  
  if(document.getElementById(str))
    console.log(str + ' existe.');
  else
    console.log(str + ' ñ existe');
}
<input type="text" id="txt"><input type="button" value="mais" onclick="busca()">

<pre>Ex.: vaca, boi, porco ou galinha</pre>

<div id='vaca'></div>
<div id='boi'></div>
<div id='porco'></div>
<div id='galinha'></div>

Now I intend to address some more details ...

Suppose there are others in the HTML document id segmented like this:

id='vaca-leiteira'

id='boi-nelore'

id='Porco_granja'

id='gaLinha_caIpirA'

Note that we have your designation followed by a hyphenate or underline, and having some variations between "vowels" and "consonants" being capital letters and/or lowercase.

How can I resolve this when typing in the text field? Type:

  • dairy cow

  • country hen

Note that I do not use hyphenate and/or underline, and put some vowel or consonant in capital letters and/or lowercase outside the scope of identification, all on purpose. I still want the right result.

In everything the riddle is, ignore these points and bring the final result. Would have to make use of some RegExp?

  • Wait, you want to treat random letters and symbols ? {@#$#@%#@%@#&} ?

  • 1

    Ah yes, I understand the question now, really need treatment

3 answers

3


Diego, follow a alternative solution that I worked out here quickly, basically what I do is take all the ids of the elements, then I remove all the special characters with .replace(/[^\w\s]/gi, ' ') and I leave them in a low box with .toLowerCase(), then simply check whether the value of the input is in the list of formatted ids, finally the code ta well self-explanatory.

function busca() {
  var str = document.getElementById('txt').value;

  var ids = pegaTodosIds();
  var idsFormatados = FormataIds(ids);

  //if (idsFormatados.includes(str.toLowerCase()))
  if (idsFormatados.indexOf(str.toLowerCase()) > -1)
    console.log(str + ' existe.');
  else
    console.log(str + ' ñ existe');
}


function pegaTodosIds() {
  var todosElementos = document.getElementsByTagName("*");
  var todosIds = [];
  for (var i = 0, n = todosElementos.length; i < n; ++i) {
    var elemento = todosElementos[i];
    if (elemento.id) {
      todosIds.push(elemento.id);
    }
  }
  return todosIds;
}

function FormataIds(ids) {
  var idsFormatados = [];
  for (var i = 0; i < ids.length; i++) {
    //console.log(ids[i]);
    var nova_str = ids[i].replace(/[^\w\s]/gi, ' ').replace('_', ' ').toLowerCase();
    idsFormatados.push(nova_str);
  }
  return idsFormatados
}
<input type="text" id="txt"><input type="button" value="mais" onclick="busca()">

<pre>Ex.: vaca, boi, porco ou galinha</pre>

<div id='vaca' class=''></div>
<div id='boi'></div>
<div id='porco'></div>
<div id='galinha'></div>
<div id='vaca-leiTeira'></div>
<div id='cavaLo_crioulo'></div>
<div id='porco-aranha'></div>
<div id='gaLinha_caIpirA'></div>

1

To do this as performatively as possible, I suggest using a map/dictionary. In Javascript, every object is a dictionary, so you’re halfway there.

Place all your elements in a dictionary. I suggest giving a common class to the elements in which you will search. For example, "agro". I.e.:

<div id="pato" class="agro"></div>
<div id="urtiga" class="agro"></div>

So you get all the elements as follows:

var elementos = document.getElementsByClassName("agro");

The getElementsByClassName method returns a vector. Now you convert the vector to a map, already normalized the keys to an all-lowercase pattern and no characters that are not accented letters. The value of each key can be anything, as long as it is logically different from false.

var mapa = {};
for (var i = 0; i < elementos.length; i++) {
    string id = elementos[i].id;
    id = id.replace(/[^a-zA-Z]/g, "");
    id = id.toLowerCase();

    mapa[id] = true;
}

Now, to know if there is any element corresponding to an informed text, it is easy:

var texto = document.getElementById('txt').value;
var input = texto.replace(/[^a-zA-Z]/g, "").toLowerCase();
var existe = !!mapa[input];

console.log(texto + (existe ? " existe" : " não existe"));
  • I’ve been trying for a long time to involve this solution of yours within the function busca() { // código do Renan }, but unfortunately the console accuses - search is not defined. What I’m doing wrong?

  • To know we need to see the code. I suggest using jsfiddle.net. The error message indicates that the search function does not exist in the scope where it is called, which can be distinguished from the scope where it was declared.

0

I am grateful to Renan and Mathias who gave me their answer, where I could reach the final result:

function busca() {

var elemento = document.getElementsByTagName('div');

    var texto = document.getElementById('txt').value;

    var campo = texto.replace(/[^a-zA-Z]/g, " ").toLowerCase();

var mapa = [];

    for (var i in elemento) {
        var identifica = elemento[i].id;
    var resultado = identifica.replace(/[^a-zA-Z]/g, " ").toLowerCase();

        mapa.push(resultado);
    }

if (mapa.indexOf(campo) > -1)
 
		console.log("Sim temos " + texto);
  	    else 
		console.log("Não temos " + texto);
}
<input type="text" id="txt"><input type="button" value="mais" onclick="busca()">

<pre>
Exemplos: vaca, boi, porco ou galinha

	- ou -

vaca Leiteira, boi nelore, Porco granja, gaLinha caIpirA'
</pre>

<div id='vaca' class=''></div>
<div id='boi'></div>
<div id='porco'></div>
<div id='galinha'></div>
<div id='vaca-leiteira'></div>
<div id='boi-nelore'></div>
<div id='Porco_granja'></div>
<div id='gaLinha_caIpirA'></div>

Explanation

The method replace with regular expression /[^a-zA-Z]/g, removes the symbols hyphenate/underline

And allied with toLowerCase(), that leaves the words capital letters in lowercase

Now we can check with if coincides.

Browser other questions tagged

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