skip to Main Content

I want to get how many time a regex matched in given string in JavaScript.

For example:

var string = "AABBCCaabbcc123!@#"

I want to get:

  • How many upper case in string: 6,
  • How many lower case in string: 6,
  • How many numbers in string: 3,
  • How many special characters in stirng: 3

Is there built-in js functions or simple way to implement this logic?

Thank you very much.

2

Answers


  1. You can try the following way:

    function countCharacters(inputStr) {
        //uppercase letters
        var uCount = (inputStr.match(/[A-Z]/g) || []).length;
        
        //lowercase letters
        var lCount = (inputStr.match(/[a-z]/g) || []).length;
        
        //numbers
        var nCount = (inputStr.match(/d/g) || []).length;
        
        //special characters
        var sCount = (inputStr.match(/[!@#$%^&*()_+{}[]:;<>,.?~\-]/g) || []).length;
        
        //return an object containing the counts
        return {
            uppercase: uCount,
            lowercase: lCount,
            numbers: nCount,
            specialCharacters: sCount
        };
    }
    
    var str = "AABBCCaabbcc123!@#";
    var counts = countCharacters(str);
    
    console.log("Uppercase count:", counts.uppercase); //6
    console.log("Lowercase count:", counts.lowercase); //6
    console.log("Number count:", counts.numbers); //3
    console.log("Special character count:", counts.specialCharacters); //3
    Login or Signup to reply.
  2. You can have this in more shorter way.Just keep the pattern correct

     var string = "AABBCCaabbcc123!@#";
    
     var uppercaseCount = (string.match(/[A-Z]/g) || []).length;
     var lowercaseCount = (string.match(/[a-z]/g) || []).length;
     var numberCount = (string.match(/d/g) || []).length;
     var specialCharCount = (string.match(/[!@#$%^&*()_+{}[]:;<>,.?~\/-]/g) 
     || 
     []).length;
    
     console.log("How many upper case in string:", uppercaseCount);
     console.log("How many lower case in string:", lowercaseCount);
     console.log("How many numbers in string:", numberCount);
     console.log("How many special characters in string:", specialCharCount);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search