Count numbers and letters from a string with javascript

Question:

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 from that same string tells me if there are numbers and how many, even without spaces this is what I have so far.

I already get how many characters but I don't want him 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;          
    }  
}

Answer:

To get the length of a string without the spaces , just remove them and get the length of the resulting string:

function lenWithoutSpaces( str ) {
  return str.replace( /\s/g, '' ).length;
}

console.log( lenWithoutSpaces( 'Hola y adiós, mundo cruel !' ) );

To count the numbers, you don't care whether the string has spaces or not: a space is not a number . You can use Array.prototype.forEach( ) , via call( ) , and passing the string as an argument.

And, for comparison, use charCodeAt( ) , which returns the ASCII code of the character at that position.

function countDigits( str ) {
  var acu = 0;

  Array.prototype.forEach.call( str, function( val ) {
    acu += ( val.charCodeAt( 0 ) > 47 ) && ( val.charCodeAt( 0 ) < 58 ) ? 1 : 0;
  } );

  return acu;
}

console.log( countDigits( 'abcde123fgh' ) );
console.log( countDigits( 'abcdefgh' ) );

Lastly, if you want it all in one call, you can return an object:

function examineString( str ) {
  var acu = 0,
      withoutSpaces = str.replace( /\s/g, '' ).length;

  Array.prototype.forEach.call( str, function( val ) {
    acu += ( val.charCodeAt( 0 ) > 47 ) && ( val.charCodeAt( 0 ) < 58 ) ? 1 : 0;
  } );

  return {
    withoutSpaces: withoutSpaces,
    digitsCount: acu,
    otherChars: withoutSpaces - acu
  };
}

console.log( examineString( 'Pues vaya, después de 10 o 15 intentos, lo encontré :-)' ) );

EDIT

To count the digits, you can also use Array.prototype.reduce( ) … it's even simpler:

function countDigits( str ) {
  return Array.prototype.reduce.call( str, function( acu, val ) {
    return ( val.charCodeAt( 0 ) > 47 ) && ( val.charCodeAt( 0 ) < 58 ) ? acu + 1 : acu;
  }, 0 );
}

console.log( countDigits( 'abcde012fgh' ) );
console.log( countDigits( 'abcdefgh' ) );
Scroll to Top