You can use a REGEX for this purpose, for example:
<html>
<body>
<p>Encuentra coincidencias en una cadena de caracteres.</p>
<button onclick="myFunction()">calcula</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = prompt("Introduce un numero", "");
if (str != null) {
alert("en "+ str +" el numero 1 se repite " + cuenta(str) +" veces.");
}
}
function cuenta(str) {
str = str.replace(/[^1]/g, "").length
return str;
}
</script>
</body>
</html>
This example introduces a string and shows you how many "1" are in the text you enter:
in 13211 the number 1 is repeated 3 times.
If you wish to search for any number (or character) you can receive by a prompt the number where you want to search and in another one you want to search, since you can create your REGEX according to what you want to search:
<script>
var coincidencia;
function myFunction() {
var str = prompt("Introduce una cadena:", "");
coincidencia = prompt("Introduce el caracter a buscar:", "");
if (str != null) {
alert("en "+ str +" el numero " + coincidencia + " se repite " + cuenta(str) +" veces.");
}
}
function cuenta(str) {
var regex = new RegExp("[^"+ coincidencia +"]","g");
str = str.replace(regex, "").length
return str;
}
</script>
I'll add the example here .