Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count appearance of each character

I'm currently working on a password strength calculator and then I need to know if a character appears more than once.
I know I must use regex like this occurance = password.match(/a/g).length to get ho many times a occurs, but I want to do that with each character (letter, number, symbol).

Is there a way to do that using JS / JQuery, maybe regex, other than working with an array which contains all characters I want to test ?

like image 534
tektiv Avatar asked Jul 24 '15 13:07

tektiv


People also ask

How do you count occurrences of a character?

Initialize a counter variable to store the count of total occurrences of a character in a string. Traverse the string character by character. If the character of the string matches with the given character, increment the value of the count variable. Finally, return the counter variable.

How do you count the occurrence of each character in a string?

Declare a Hashmap in Java of {char, int}. Traverse in the string, check if the Hashmap already contains the traversed character or not. If it is present, then increase its count using get() and put() function in Hashmap. Once the traversal is completed, traverse in the Hashmap and print the character and its frequency.


1 Answers

Something like this?

var hello = "Hello world";
var histogram = {};

for (var i = 0, len = hello.length; i < len; i++) {
    var letter = hello[i];
    histogram[letter] = (histogram[letter] || 0) + 1;
}

console.log(histogram);

Result:

{ H: 1, e: 1, l: 3, o: 2, ' ': 1, w: 1, r: 1, d: 1 }

Or you may use array. Just change {} to [].

like image 111
Pitel Avatar answered Sep 20 '22 12:09

Pitel