Hola
joaco87:
Realmente no necesitas fabricarte una función que cuente por la fuerza las incidencias, javascript ya tiene una nativa, se llama
match(). Es algo complicada, pero aporta mucha información para tus búsquedas de texto. Puedes buscar más información acerca de ella por la web.
Lo que quieres se podría hacer así:
Código PHP:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="es" lang="es">
<head>
<meta http-equiv="Content-type" content="text/html;charset=iso-8859-1" />
<meta name="Author" content="derkeNuke" />
<title>Página nueva</title>
<style type="text/css">
</style>
</head>
<body>
<script type="text/javascript">
<!--
// document.getElementById abreviado
function $(x) { return document.getElementById(x); }
function buscar() {
var donde = $("texto").value;
var que = $("caracter").value;
var re = new RegExp(que, "gi");
alert( donde.match(re).length );
}
// -->
</script>
<textarea id="texto">La casa de Pepito es particular</textarea>
<br/>
<label for="caracter">Escriba un caracter: </label>
<input type="text" id="caracter" size="13" value="a" />
<br/>
<input type="button" value="Buscar" onclick="buscar();" />
</body>
</html>
Y según el método que tú estabas utilizando, que estabas cerca, podría ser así la función
buscar():
Código PHP:
function buscar() {
var apariciones=0;
var x = $("texto").value;
var c = $("caracter").value;
for(var i=0; i<x.length; i++) {
if( x.charAt(i).toUpperCase() === c.toUpperCase() ) apariciones++;
}
alert(apariciones);
}
Espero que hayas entendido.
Saludos.