# How can I count the repeated digits of a number in javascript [closed]

1

How can I count the repeated digits of a number entered in a javascript prompt?

That is, they ask me that when the user enters the number in the prompt, determine how many times the number "1" is repeated in that number and if there is no number "1" say that there is not.

If someone could explain how to do it, it would be very helpful.

PS: excuse my ignorance!

asked by Elvis David Taveras Lara 26.03.2016 в 01:44
source

1

I guess it's not a "real" problem but an exercise in loops, in that case I guess the expected response looks like this:

``````    <!DOCTYPE html>
<div id=out></div>
<script>
var busqueda="1";
var respuesta;
out.innerHTML = respuesta;
</script>
``````

The idea is that, the entry is considered a "string" where it is treated as an array of characters, so you only have to go through all its positions counting how many times the desired character appears.
In "real" problems it is shorter and more useful to use regex.

source
2

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 .