Basic JS exercise: simple text search

Asked

Viewed 150 times

6

I was trying to create a JS search to find a given name in the body of a text. However, the search does not return any value. The logic I used is:

<script>
var text = "Xxxxx, xxxx x xxxx x xxxx xxxxxx xxxxxxx. Lucas Menezes";
var myName = "Lucas";
var hits = [];
for (var x = 0; x < text.length; x = x + 1) {
    var adiction = myName.length + x;
    if (text[x] === "L") {
        if (text[adiction] === "s") {
            for (var i = x; i < adiction; i = i + 1) {
                hits.push(text[i]);
            };
        };
    };
};
if (hits.length === 0) {
    console.log("Your name wasn't found");
    console.log(adiction);
} else {
    console.log(hits);
    console.log(adiction);
}
</script>

Could someone help me by telling me what the problem is? The array hits empty turn. If remove the second IF it even works, however returns me an inaccurate search presenting any name that begins with L and the 4 subsequent characters.

  • What result do you expect?

  • I was hoping the hit array would bring me: [L,u,c,s]

  • rsrsrs sorry. I’m new around here

  • I get it, you need to do it this way, or another way would do it too?

  • Actually brother, it is only a basic exercise, I am new in programming. If it is possible that way, I thank you. But if you find another convenient way for a beginner. I’m already very grateful.

4 answers

9

You do not need to do this search "on the nail", character by character. It is easier to use indexOf:

var text = "Xxxxx, xxxx x xxxx x xxxx xxxxxx xxxxxxx. Lucas Menezes";
var myName= "Lucas";
var position = text.indexOf(myName);
console.log(position)

You can also use regular expressions:

var text = "Xxxxx, xxxx x Lucas x xxxx xxxxxx xxxxxxx. Lucas Menezes";
var myName= "Lucas";
var re = new RegExp("(\\b" + myName + "\\b)", 'g')
var found = re.exec(text);
console.log(found)

Probably in real life you would use one of these, or Antonio Alexandre’s suggestion, and hardly sweep the string to each character. But I understand that it is a programming exercise, as you said in one of the answers. In this sense it is totally valid. The user already explained well what the problem was. I’m just finding it strange that you want to save as a result the very text you searched. It would be more useful to assemble an array like this:

[12, 27, ...]

In this case, you would save the (initial) position where each occurrence was found in the larger string. It is as a suggestion.

4


The problem is on this line:

var adiction= myName.length + x;

Whereas the index starts from 0, in a string of size 5 you will get indexes from 0 to 4. So if you add the size of the string you will be trying to access the index 5.

Therefore it is necessary to subtract 1 from its final index.

var adiction= myName.length + x - 1;
  • I applied what told me brother, and it worked, however returned me [L,u,c,a]. But it already served so that he did not select other words with initial L.

  • In this case, change the line "for(var i = x; i < adiction ; i = i + 1)" by "for(var i = x; i <= adiction ; i = i + 1)"

  • Exactly! Thank you beast! Only I did not understand why if I removed the 2nd conditional the search brought me results, and after it, neither appeared the result of "not found", or any logic error, only the empty array. But thank you very much brother.

3

The question is already answered, but for those interested can follow another way of locating text elements using string.search that can be adapted to different uses.

<script>

texto_original = '';

window.onload=function()
{
	texto_original = document.getElementById("texto").innerHTML;
}

function busca()
{
	// Pega o conteúdo original da div com id = texto
	texto = texto_original;
	
	// Pega o termo que se quer buscar
	var termo_busca = document.getElementById("busca").value;
	
	var termo_len = termo_busca.length;
	
	var partes = new Array();
	
	partes_i = 0;

	//enquanto está achando termo_busca
	while(texto.search(termo_busca) != -1)
	{
		
		pos_proximo = texto.search(termo_busca);
		current_position = pos_proximo + termo_len;
				
		partes[partes_i] = texto.substring(0, pos_proximo); 

		//alert("Parte " + partes_i +": " + partes[partes_i]);		

		texto = texto.substring(current_position, texto.length); 		
		
		//alert("Novo texto: " + texto);		
		
		partes_i = partes_i + 1;		


	}
	partes[partes_i] = texto;
	
		
	var glue = '<span class="destacado">' + termo_busca + '</span>';
	

	var novo_conteudo = partes.join(glue);

	
	document.getElementById("texto").innerHTML = novo_conteudo;
	
}
</script>

<style>
.destacado { background-color:yellow;}
</style>



<input type="text" id="busca" value="Lucas"> <input type="button" value="Buscar" onclick="busca()"> 

<br><br>

<div id="texto">
111 xxx xxx Lucas xxx xx222 xxxx xxxx Lucas xxxx 333x xxxx xxxx
</div>

Edited on 27/01/2017 at 17:08:

Now there is another way to do the same thing as the code above, only using javascript replace. The difference is that with replace one writes less code, but does not save the pieces, so this code below does not give as much room for modifications.

<script>

texto_original = '';

window.onload=function()
{
	texto_original = document.getElementById("texto").innerHTML;
}


function busca_replace()
{
	// Pega o conteúdo original da div com id = texto
	texto = texto_original;
	
	// Pega o termo que se quer buscar
	var termo_busca = document.getElementById("busca").value;
	
	trocar_por = '<span class="destacado">' + termo_busca + '</span>';

	// criando expressão regular com a opção g e o termo_busca pra poder passar para o replace
	var regxp = new RegExp(termo_busca,"g"); 
	
	// Referência: http://stackoverflow.com/questions/494035/how-do-you-use-a-variable-in-a-regular-expression
	
	texto = texto.replace(regxp,trocar_por);
	
	document.getElementById("texto").innerHTML = texto;
}

</script>

<style>
.destacado { background-color:yellow;}
</style>


<input type="text" id="busca" value="Lucas"> <input type="button" value="Buscar" onclick="busca_replace()"> 

<br><br>

<div id="texto">
111 xxx xxx Lucas xxx xx222 xxxx xxxx Lucas xxxx 333x xxxx xxxx
</div>

  • Thanks for sharing friend! Very useful your syntax.

  • Valew Lucas, anything just talk. By the way I will increase the answer with another way to do this same search for cases where it is necessary to just change the text, using your variabletext.replace(look for this, change) passing instead a regular expression with the option g to be able to find all occurrences.

0

See if it suits you:

var myText = "xxxx XXXX xxxx xxxx Junior Nunes";
var myName = 'Junior';


if(myText.indexOf(myName) != -1) {
  var hits = myName.split('');  
  console.log(hits);
}
else {
  console.log('O nome não foi encontrado');
}

The indexOf looks for a piece of text inside the string, if it does not find it returns -1.

If you find I’ll take the variable myName which contains the string with the name and divides all letters inside an array with the split.

I think this is a simpler way of understanding...

NOTE: If you have any questions, comment there that I explain you better!

Edited

This one is made with for!!

var myText = "xxxx XXXX xxxx xxxx Junior Nunes";
var myName = 'Junior';

var status = 'Não achou';

for(var i = 0; i < myText.length; i++) {
  if(myText[i] == myName[0]) {
    if(myText.substr(i, myName.length) == myName) {
      status = 'Achou';
      break;
    }
  }
}

console.log(status);

  • Nice guy. Yes, it works, however I think I can only use the tools I have so far. If...Lse / while / for... these basic conditions. But I am very grateful for the help beast. I will definitely write down the index0f.

  • rsrsrsrs. Your example has more of a search for truth (hence you destroy it with the split!) to leave in the format I asked for. KKK I believe the next step would be to just join the array into a string. KKK Even worth brother!

  • @Lucasmenezes I edited and put a code using for, but I think the top one is even simpler...

  • But it returns "Found". In addition to using substr that I have not yet seen. But do not worry brother dsmoreira showed me how to make a small change in that initial syntax to return to me what I asked. Still it was worth it by force.

Browser other questions tagged

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