daniel-g of Nett
3/14/2017 - 10:16 PM

Búsqueda de texto en javascript

Búsqueda de texto en javascript

<html>
<head>
	<meta charset="UTF-8">
	<title>Ejercicio 1</title>
</head>
<body>
	<div>
		<p>TEXTO COMPLETO</p>
		<textarea rows="4" cols="50" id="rollo">David bla Daniel, pero Daniel hasn't been found around, no Davin</textarea>
	</div>
	<div>
		<p>Texto a Buscar</p>
		<form action="javascript:void(0);" onsubmit="contador();">
			<input type="text" name="fname" id="keyword" value="David">
			<button type="submit" id="boton">Buscar</button>
		</form>
	</div>
	
	<div>
		<p>Resultados</p>
		<p id="results"></p>
	</div>


	
</body>
</html>
function contador() {
	
	var textOriginal=document.getElementById("rollo").value;
	var text=textOriginal.toLowerCase();
	var myNameOriginal=document.getElementById("keyword").value;
	var myName = myNameOriginal.toLowerCase();
	var ocurrencia="";
	hits=0;

	for(var i=0; i<text.length; i++){ //recorre el texto
	    if(text[i]===myName[0]){ //busca la letra D
	        for(var j=i;j<i+myName.length;j++){ //
	           ocurrencia=ocurrencia+text[j]; 
	        }
	       if (myName == ocurrencia) {hits+=1;} 
	       ocurrencia="";
	    }
	}


	if(hits==0){
		document.getElementById("results").innerHTML = "No se encontraron resultados";
	} else {
		document.getElementById("results").innerHTML = "Número de veces que fue encontrado "+ myNameOriginal + ": "+ hits;
	}
}

document.getElementById("boton").onclick = function() {clickar()};

function clickar() {
  contador();
}