计算每个字符的出现 [英] Count appearance of each character
本文介绍了计算每个字符的出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前正在使用密码强度计算器,然后我需要知道一个字符是否出现多次.
我知道我必须像这样occurance = password.match(/a/g).length
使用regex
来多次出现a
,但是我想对每个字符(字母,数字,符号)执行此操作.
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).
除了使用包含我要测试的所有字符的数组之外,是否可以使用JS/JQuery(也许是正则表达式)来做到这一点?
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 ?
推荐答案
像这样吗?
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);
结果:
{ H: 1, e: 1, l: 3, o: 2, ' ': 1, w: 1, r: 1, d: 1 }
或者您可以使用数组.只需将{}
更改为[]
.
Or you may use array. Just change {}
to []
.
这篇关于计算每个字符的出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文