js:找出字符串中重复数量最多的字母

Jan 30 2019 Node.js

1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var str = 'cbdefdfpoweqwlkjsaaaaz'
function findMostLetter(str) {
// 去除空格并排序
let match = str
.replace(" ", "")
.split("")
.sort()
.join("")
.match(/(\w)\1*/g);
let res = "";
let len = 0;
match.forEach((val, key) => {
if (val.length > len) {
res = val[0];
len = val.length;
}
});
return res;
}

findMostLetter(str)

2

1
2
3
4
5
6
7
8
9
10
11
12
13
function test(str) {
return str
.replace(" ", "")
.split("")
.sort()
.join("")
.match(/(\w)\1*/g)
.sort((x, y) => x.length - y.length)
.pop()[0];
}

const res = test("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa dddddddfdf");
console.log(res);