一、对象法:以下面的例子为例,把一个字母作为对象的属性名,字母出现的次数作为属性值;进而比较属性值的大小。
\1:第一个括号对应的内容。
```html:run
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
var str = 'SSSadsdccCCCAdkdkkkkDccdddaaaccCCsSSSSSs';
function maxstr(str) {
var obj = {};
var maxNum = 0;
var maxVal = "";
for (var i = 0; i < str.length; i++) {
var strNum = str.charAt(i).toLowerCase();
if (obj[strNum]) {
obj[strNum]++;
} else {
obj[strNum] = 1;
}
}
for (var attr in obj) {
if (obj[attr] > maxNum) {
maxNum = obj[attr];
maxVal = attr;
} else if (obj[attr] == maxNum) {
maxVal += attr
}
}
return "出现次数最多的字母是:" + maxVal + ";次数是:" + maxNum
}
var valNum = maxstr(str);
document.write(valNum);
</script>
</body>
</html>
```
二、排序法:以下面的例子为例,先对它们进行排序,再取出小分组和小分组被匹配的次数。
**html 代码**
```html:run
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
var str = 'SSSadsdccCCCAdkdkkkkDccdddaaaccCCsSSSSSs';
function maxstr(str) {
var maxNum = 0;
var maxVal = "";
str = str.split('').sort(function (a, b) {
return a.localeCompare(b)
}).join('');
/*str = str.split('');
str = str.sort(function (a, b) {return a.localeCompare(b)});
str = str.join('');*/
str.replace(/(\w)\1+/gi, function (totalRegexp,firstGroup) {//前面正则的意思是:"(\w)"字符、"\1"第1个括号、"+"1次到多次
if (totalRegexp.length > maxNum) {
maxNum = totalRegexp.length;
maxVal = firstGroup;
} else if (totalRegexp.length == maxNum) {
maxVal += firstGroup;
}
});
return "出现次数最多的字母是:" + maxVal + ",次数" + maxNum;
}
var valNum = maxstr(str);
document.write(valNum);
</script>
</body>
</html>
```
转载于:https://www.cnblogs.com/gushixianqiancheng/p/10967018.html