From a string I need to know how many characters there are without counting spaces or numbers and send it to print, as well as another function that tells me if there are numbers and how many of that same string, even without spaces, this is what I have done so far.
I already get how many characters but I don't want it to count the numbers, I want them separately:
function cadenaNumerosLetras(){
var frase = document.getElementById(‘cadena’).value;
var letterCount = frase.split(/\W/).join('').length;
var contadorLetras = letterCount.toString();
console.log(letterCount);
document.getElementById(‘resultado’).value = contadorLetras;
var numeros = "0123456789";
if(!isNaN(frase)){
for(i=0; i<frase.length;i++){
if(numeros.indexOf(frase.charAt(i),0)!=-1){
return 1;
document.getElementById('numeros').innerHTML= frase;
}
}
return 0;
}
}
To get the length of a string without the spaces , just remove them and get the length of the resulting string:
To count numbers, you don't care if the string has spaces or not: a space is not a number . You can use
Array.prototype.forEach( )
, throughcall( )
, and passing the string as an argument.And, for comparison, use
charCodeAt( )
, which returns the ASCII code of the character at that position.Lastly, if you want it all in one call, you can return an object:
EDIT
To count the digits, it can also be used
Array.prototype.reduce( )
... it's even simpler:A variation on @Trauma's answer , making reduce more elegant :
Long live Functional Programming!
According to what you say, you need:
I would use the callback of
replace()
, passing it 2 regular expressions,[^\s^\d]
and\d
respectively, in order to get everything you need together at once:If you just want the amounts, you can use
reduce()
andtest()
:I think that the problem can also be solved in a simple way with more common functions like
split()
,join()
andfilter()
:You can compare the results of the examples with those of other answers and you can see that they are the same.
I hope I have contributed to solve the problem, greetings.